Utilizing radio buttons within an ng-repeat loop in AngularJS

At the moment, I am facing an issue with setting up an array of options for the user to choose from. Here is how my setup looks:

Here are the available options:

 $scope.licenses = [...]

The currently selected option is:

 $scope.selectedLicense = $scope.licenses[0];

In my HTML code, it appears as follows:

    <ul>
        <li ng-repeat="lic in licenses">
            <input type="radio" ng-model="selectedLicense" value="lic"></input>
                {{lic.nrOfLicenses}}
        </li>
    </ul>

However, upon loading the page, no radio button is automatically pre-selected.

You can find a working example here: http://jsfiddle.net/HB7LU/9765/

I can't seem to figure out what might be causing this issue. Any ideas on where I may have gone wrong?

Answer №1

When using the ng-repeat directive, a new scope is created for each iteration

For more information, refer to the official documentation

Each template instance has its own scope

Therefore, when looping through, there exists a scope variable named selectedLicense in each child scope. Consequently, your $scope.selectedLicense will not be bound to the radio buttons as expected.

You can utilize prototypical inheritance to overcome this issue. Learn more about JavaScript Prototypal Inheritance

$scope.x = {};
$scope.x.selectedLicense = $scope.licenses[0].nrOfLicenses;

<input type="radio" ng-model="x.selectedLicense" ng-value="lic.nrOfLicenses"></input>
// Angular first searches for `selectedLicense` in the child scope, then looks for x object in the parent scope when it doesn't find it in the child scope.

Check out the demo Fiddle


In the example above, the radio buttons are bound to the nrOfLicenses property within the object.

If you wish to bind the radio button to the entire object, follow these steps:

$scope.x = {};
$scope.x.selectedLicense = $scope.licenses[0];

<input type="radio" ng-model="x.selectedLicense" ng-value="lic"></input>

Here's the demo Fiddle

Answer №2

It is recommended to utilize the ng-value directive instead of value, as this allows you to work with your scope object effectively.

<input type="radio" name="license" ng-model="selectedLicense" ng-value="lic"></input>

Check out this example on jsFiddle

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

Using MUI with React Hook Form: Initially fill out the TextField value, only to find it unmodifiable thereafter

Utilizing the MUI + React Hook Form combination, I've developed a CustomTextField.tsx component to ensure smooth functionality. // CustomTextField.tsx import { TextField } from "@mui/material"; export default function CustomTextField(props: ...

"Subscribing to a Meteor collection results in the entire collection being returned

I've been working on implementing a publish/subscribe architecture for my Meteor application. Although I have not removed the autopublish package yet, everything seems to be working smoothly with React and plugins like kadira:flow-router and kadira:re ...

What is the most effective way to update a variable from a function in Angular?

I have textboxes within an ng-repeat block. To detect changes from the original content, I store the original data in a variable. <tr data-ng-repeat="p in products"> <td> <textarea data-elastic data-ng-model="p.comment" data-ng-change ...

Capturing an error within an asynchronous callback function

I am utilizing a callback function to asynchronously set some IPs in a Redis database. My goal is to catch any errors that occur and pass them to my error handling middleware in Express. To purposely create an error, I have generated one within the selec ...

Is it possible to create a personalized serialize form when sending an AJAX POST request

How can I format form data on an AJAX POST request differently than the default $("#formid").serialze()? The current result is not suitable for my needs, as it looks like this: `poststring="csrfmiddlewaretoken=bb9SOkN756QSgTbdJYDTvIz7KYtAdZ4A&colname= ...

Tips for effectively handling numerous events from multiple Slickgrid instances on a single page

I'm encountering an issue with utilizing multiple Slickgrids on a single page. With the number of grids changing dynamically, I generate them within a JavaScript function and maintain them in a grid array as shown below. var columns = []; var options ...

JavaScript dropdown menu that dynamically changes colors

<!DOCTYPE html> <html> <head> </head> <body> <script> var redtoggle=false; function togglered() { redtoggle = !redtoggle; if (redtoggle) { document.getElementById("txtInput").style.color = "red"; } else { do ...

Determine which array within an object is the longest in terms of length

Currently, I'm incorporating lodash.js into my project but it seems that there is no built-in method to achieve what I need. Even after attempting it on my own, I find myself dissatisfied with the outcome. function findLargestArrayInObject(object) ...

Unable to change the AJAX variable that was returned

I have a JavaScript/jQuery script that fetches an external HTML page using AJAX and then applies a function to all its text nodes. $.get('webpage.html', function (html) { $(html).find('*').each(function () { $(this).content ...

A Guide to Performing Dual API Calls within Angular for a Single Component

Is there a way to make two separate API calls within the same Angular component? For instance, I have an order component that is rendered twice in a tabular manager on a page. Using ngif condition, I display different data for TAB1 and TAB2. The issue is ...

Retrieve all data entries added today on Mongo, specifically for beginners

Is there a way to query entries in Mongo that were added today only? For instance, if I added something at 9 am, I want only that entry and not one added at 9 pm the previous day. I'm struggling with how to structure the query properly. const db = ...

The display of data in Datatables is malfunctioning

I have already included the provided CDN on the website but I am still unable to display any results even after copying and pasting every line of code. Here is the CDN <link rel="stylesheet" type="text/css" href="https://cdn.d ...

Is there a way to prevent a page from redirecting when a checkbox is clicked?

I am currently working on this code snippet: <div onClick="$(location).attr('href','updateUser.php?id=<?php echo $admin->id; ?>')" class="dbItem"> <div class="dbItemCheckbox"> < ...

The FormData() object in Django backend is consistently found to be void of any data

I am currently experimenting with uploading an HTML form through AJAX using pure JavaScript, without jQuery. The form is put together in my template by combining three components: the CSRF token, a ModelForm, and a regular Django form (forms.Form). The vis ...

Utilize Google Cloud Endpoints for uploading files to a Google App Engine application

Currently, I have a setup where I am using Google App Engine for my server-side application written in python. This server is serving as the back-end for my web application which is written in PHP. The communication between the two is handled through clien ...

Angular-maps-google search bar

I have a specific directory structure as follows: myFolder myApp.coffee index.html searchbox.tpl.html Within myApp configuration, I've set the following: $scope.searchbox = {template: "searchbox.tpl.html"} While trying to implement this example, ...

Angular is not providing the anticipated outcome

I'm new to Angular (7) and I'm encountering an issue while trying to retrieve the status code from an HTTP request. Here's the code snippet used in a service : checkIfSymbolExists() { return this.http.get(this.url, { observe: 'res ...

Learn how to display only certain elements when triggered by the click of another

I have developed a tab system where each tab contains a unique set of questions and answers. The structure of the tabs is exactly as I envisioned, but I am facing challenges with toggling the display of answers when their respective questions are clicked. ...

Angular concise conditional statement

I need help making a statement based on a value for the first time in Angular. I currently have two elements that check the value, but I don't like that. Here is my code: <h4 class="modal-title" ng-show="::model.trainingModel.name !== undefined"&g ...

Transform a JSON array containing individual objects into a new JSON array with objects

My array contains objects with nested objects in each element, structured like this: [ { "person": { "name": "John", "isActive": true, "id": 1 } }, { "person": { "name": "Ted", "isActive": true, "id": 2 } } ] I ...