Display a DIV using Angular.js upon checking a radio-input option

I need to display a specific div when a input-radio is selected.

<div>
  <div class="radio c-radio">
    <label>
      <input type="radio" name="specialType" ng-model="vm.specialType.closed" />
      <span class="fa fa-check"></span>First Radio
    </label>
  </div>
  <div ng-show="vm.specialType.closed">
    <label>Day: </label>
    <input type="date" class="form-control" />
  </div>
</div>

I have a total of 4 radio inputs set up similarly. I want each one to show or hide based on the selection made. I attempted using ng-click='someFunction()', but it wasn't effective, and I am searching for a better approach.

If, for instance, the first radio is checked, and then the third is selected, I aim to hide the currently visible div and reveal the first one again.

In my controller, there's a variable structured like this. Initially, I planned to use it to toggle between true and false values for show/hide purposes. However, I'm open to exploring more elegant and streamlined solutions.

vm.specialType = {
  closed: false,        //1st radio
  open: false,          //2nd radio
  ownGuards: false,     //3rd radio
  foreignGuards: false  //4th radio
};

Answer №1

If you're looking to display only one div at a time, consider using a single variable that determines which div should be visible. This approach simplifies the process and requires only one model.

To control the visibility of each div, compare the div's number with the value of the model. Each radio button assigns its unique value to the model.

  <div>
    <div ng-show="vm.which==1"><h1>1</h1></div>
    <input type="radio" ng-model="vm.which" name="vis" value="1" />
  </div>
  <div>
    <div ng-show="vm.which==2"><h1>2</h1></div>
    <input type="radio" ng-model="vm.which" name="vis" value="2" />
  </div>
  <div>
    <div ng-show="vm.which==3"><h1>3</h1></div>
    <input type="radio" ng-model="vm.which" name="vis" value="3" />
  </div>
  <div>
    <div ng-show="vm.which==4"><h1>4</h1></div>
    <input type="radio" ng-model="vm.which" name="vis" value="4" />
  </div>  

You can view the code in action on this plnkr link.

To handle multiple similar divs efficiently, consider using arrays and ng-repeat. This is considered best practice for managing common elements within different divs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating between pages in a multi-page setup using vue.js: A comprehensive guide

I came across a helpful post at this link about implementing multiple pages in Vue.js CLI. After setting up multiple pages, I was excited to test it out. However, I encountered an issue when trying to access the different pages from the URL http://localho ...

Could not locate the provider: $stateProvider

It's puzzling to me why this code is not recognizing the $stateProvider. Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: Error: [$injector:unpr] Unknown provider: $stateProvider This is a simple example of a module: ( ...

Ordering an array based on two integer properties using JavaScript

Here is an array of objects I am working with: const items = [ { name: "Different Item", amount: 100, matches: 2 }, { name: "Different Item", amount: 100, matches: 2 }, { name: "An Item", amount: 100, matches: 1 }, { name: "Different Item" ...

Conceal and reveal div elements with the power of JavaScript

Within my webpage, I have two DIV elements named DIV1 and DIV2. I am able to toggle between hiding and showing each one individually. Is it possible for DIV1 to be displayed automatically when the page loads, and then upon clicking a button to show DIV2, ...

Onload, capture page elements, delete them, and then access the original content

I am encountering two DIV elements on my page that I need to capture upon loading the page and preserve their contents until the page is refreshed. The nested DIV element is contained within the other one. After locating these elements initially, I want t ...

Avoid making redundant ajax requests in AngularJS

I am currently utilizing express-jwt for constructing a restful api. The client is sending duplicate ajax calls - the first call initiated by AngularJS resulting in a 204 response code, and the second call initiated by another source resulting in a 200 res ...

Having trouble with jQuery's getJSON function throwing an error?

I have been working on a project where I am using the getJSON function to fetch JSON data from an API that I am developing. However, I am facing an issue where the getJSON function always triggers the error handler. Below is the JavaScript code I am using: ...

Accessing a file url with Firefox using protractor

I am currently facing a challenge with Protractor as I try to access an HTML file as a website using it. Whenever I attempt to do so, I encounter an error from Protractor stating: Failed: Access to 'file:///C:/filelocation/index.html' from s ...

What is the best way to extract user input and pass it to an AJAX request URL?

Recently, I successfully completed an AJAX request using AngularJS. You can check out the code here. Everything was working perfectly until I tried to add a dynamic variable (city) to the link like this: $http.get('http://api.wunderground.com/api/KEY ...

Is there a more efficient way to handle post data without increasing its size when encoding JSON within a URI

I have a significant amount of data to post, and it needs to be minimized for performance reasons. Initially, my data consists of JavaScript objects which I then convert to JSON format before sending it via POST request. The issue is that my data include ...

Error encountered - Unable to read the property 'map' of an undefined array

Having multiple values to send, such as those needed for customer user creation. Here is where I found a solution: (Using an object array as input data) I adapted the code to extract only the true knowledge values. Upon inspecting my button, an error o ...

Using Angular 4 to transfer data from a dynamic modal to a component

Currently implementing material design, I have set up a dialogService for dynamically loading MdDialog. My goal is to create a search dialog with filters that, upon submission, directs the user to a search-results component route. However, I am struggling ...

Is Eval really as bad as they say... What alternative should I consider using instead?

After making an ajax request, a JSON array filled with user inputs is returned to me. The inputs have already been sanitized, and by utilizing the eval() function, I can easily generate my JavaScript object and update the page... However, there lies a dil ...

jQuery .On() not triggering event when passing parameters from object

Having issues with a Chrome extension where the .On() callback is not firing and the click event is not being attached to the elements as expected. There are no errors in the console and debugging indicates that the correct values are being passed to the ...

Utilizing Express middleware to handle asynchronous operations with next and Promises

Here is a very basic Express router with a handler: router.get('/users/:userId/roles/:roleId', function(req, res, next){ const roleId = req.params.roleId; res.rest.resource = UserModel.findOne({ _id: req.params.userId}).exec().then(funct ...

Guide to using Puppeteer for downloading PDFs from a website

My goal is to utilize Puppeteer for downloading PDF files from a particular website. However, I am unsure how to instruct it to download all the files automatically. For instance: One file on the website follows this format: example.com/Contents/xxx-1.pdf ...

The data type of Subscription: prototype, NOT ASSIGNED

I am encountering the following error when attempting to return a subscription object. Error Message:-------- Type 'Subscription' does not have the prototype and EMPTY properties that are expected from type 'typeof Subscription' Here ...

Tips for optimizing an AJAX website for search engine crawling

If you're looking for an example of a crawlable AJAX website utilizing HTML5, CSS3, and history.pushState(), check out the following site: (for more information, visit ) However, keep in mind that this site assumes server-side ...

Dynamic bullseye displayed on a Vis.js network node

I am currently utilizing Vis.js to create network diagrams. I am interested in adding a notification feature where when an AJAX update is received for a specific node, the canvas will move that node to the center (which Vis.js can already do). Following th ...

The type 'SVGPathSeg' cannot be assigned to type 'EnterElement' because the property 'ownerDocument' is not present in type 'SVGPathSeg'

I'm attempting to replicate this example using the d3-ng2-service service on Angular 5. Component: OnInit code: let d3 = this.d3; let d3ParentElement: Selection<HTMLElement, any, null, undefined>; let d3Svg: Selection<SVGSVGElement, any, n ...