Error with ngModel on radio inputs within an ngRepeat

Plunk: http://plnkr.co/edit/Y4ntAj2fIIpexKjkCvlD?p=preview

In an attempt to develop a form component that allows users to create multiple instances of a specific data field, I am facing an issue where the radio buttons are not updating the selected item as expected. Each radio button is generated using 'ng-repeat', with its value set to the index from the repeat loop. The radio buttons are linked to '$scope.selectedItem' to direct the inputs to the correct item.

Strangely, despite the radio buttons changing their selected state, the 'selectedItem' variable remains unchanged. Interestingly, a similar setup with static radio buttons worked fine, suggesting a possible problem with 'ng-model' within 'ng-repeat'.

Answer №1

To ensure proper functionality, it is necessary to include ngModel for each button. Since each iteration of ngRepeat creates a new isolate scope, there are two ways to reference the variable in the parent controller:

  1. One option is to change selectedItem to an object. This works because objects are passed by reference in JavaScript, unlike primitives which do not support two-way binding.

  2. The second option is to add $parent.selectedItem, which allows you to reference the scope variable selectedItem in the controller.

Regardless of the method chosen, it is essential to use ngModel for each button.

Option 1:

<input type='radio' 
       name='select' 
       id='{{$index}}' 
       ng-value='$index' 
       ng-model='$parent.selectedItem'/>

View Example using $parent

Option 2:

JS:

$scope.selectedItem = {id: -1};

HTML:

<input type='radio' 
       name='select' 
       id='{{$index}}' 
       ng-value='$index' 
       ng-model='selectedItem.id'/>

(Make sure to update any references to selectedItem to selectedItem.id)

View Example using an object for selectedItem

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

Employing a lexicon of hexadecimal color code values to harmonize CSS styles

I have a unique requirement where I need to utilize a dictionary of HTML color codes and then apply those colors as styles. It's an interesting challenge! Here is an example of how my color dictionary looks like: const colorCodes = { red: ...

Improving the efficiency of JSON data retrieval in JavaScript

I possess a hefty 10MB JSON file with a structured layout comprising 10k entries: { entry_1: { description: "...", offset: "...", value: "...", fields: { field_1: { offset: "...", description: "...", ...

Updating an array within a service across different controllers in AngularJS

My goal is to create an array within a service that can be updated from different controllers. The purpose of this setup is to ensure that the array is accessible across all controllers. I need the ability to add new items to the array as well as delete ex ...

Tips on adding line breaks after periods that are not at the end of a sentence in HTML text nodes with regular expressions

Looking to craft a regex that can identify all periods not enclosed in quotes and not followed by a '<'. This is for the purpose of converting text into ssml (Speech Synthesis Markup Language). The regex will be utilized to automatically inse ...

Get the host name using Node.js server without using the 'req' parameter

Currently, I am utilizing req.headers.host to identify the host name of the server, which works well when dealing with incoming requests at the server. However, I am curious about how one can determine the host name without a request (i.e. without req). T ...

Changing the contents of a global array in JavaScript

$(document).ready(function(){ var currArray=null; var group=null; var admin=null; var equipment=null; var student=null; console.log("after get array info"); for(var i=0; i<equipment.length; i++) { console.log("equipment at index after get array info ...

Does the awaitMessages filter not execute the .then function?

I am currently implementing a direct message prompt in my bot, where the player must respond before the bot proceeds with further questions. I have set up a filter to prevent the bot from detecting and acknowledging its own message. However, for some reaso ...

Adding products to an owl-carousel in an HTML document using JavaScript

When I try to add my products to an owl-carousel using JavaScript, the display is not correct. My HTML code looks like this: <div class="container mt-5 mb-5" data-aos-anchor-placement="top-center"> <div class="owl-carouse ...

The functionality of Laravel's Input::get('params.id') feature may be affected if a custom HTTP header is included in the post request

Currently, I am using Angular on the client side and Laravel on the back end. However, when attempting to retrieve the parameters sent to Laravel using input::get('params.id'), I am consistently getting null: $http.defaults.headers.post = {&apos ...

How to Align Text at the Center of a Line in Three.js

Exploring What I Possess. https://i.sstatic.net/nAtmp.png Setting My Goals: https://i.sstatic.net/svcxa.png Addressing My Queries: In the realm of three.js, how can I transform position x and y into browser coordinates to perfectly align text in th ...

Omit NPM packages from being updated

Currently, I am utilizing npm for managing my React Native project, and I am faced with the challenge of excluding certain packages during the process of npm update. Specifically, I am aiming to maintain my React package at all times on <a href="/cdn-c ...

Using Jquery UI dialog to ensure validation

function DisplayDialog() { $("#dialogid").dialog({ width: 300, modal: true, show: 'drop', hide: 'drop', buttons: { "Ok": function () { return true; $(this).dialog('close'); }, "Cancel": func ...

Access the JSON data stored in the File Directory by reading and utilizing it for your project

Can someone help me figure out how to retrieve data from the xmltojson.json file and assign it to a variable using JavaScript? const jsonfile = require('jsonfile') const file = 'xmltojson.json' jsonfile.readFile(file, function (err, obj ...

[VUE Alert]: Rendering Error - "Sorry, there is a type error: object is currently undefined."

<script> const app = new Vue({ el: '#app', data:{ results:{} }, mounted() { axios.get('{{ route('request.data') }}').th ...

Create a list using ReactJS

I've been working on rendering a dynamic list in JSX, but I'm facing issues displaying the items. Below is my code snippet where I attempted to use useState const [orderList, setOrderList] = useState([]) and setOrderList(prev => [...prev, chil ...

Assigning values to objects in Vue: setting data properties

I am working with a Vue.js app and attempting to update a value inside an object. Specifically, I want to change the 'name' value when the @change="onfilechangev" event occurs. Is there a way to achieve this, or is it not possible to update an ob ...

Problem with Pathjs routing

Can anyone help with this routing issue I'm having? Path.map("/(:page_1)(/:page_2)/").to(funct); The route is not matching for: /projects/index2/ It matches /anything, but not /anything/anything If you have any ideas, please share! ...

What are the steps to set up express.static to retrieve static files from the Google Cloud CDN?

I'm in the process of hosting an Angular application on Google Cloud App Engine. I am utilizing Express to serve the content, and I want the static files to be delivered from the Google CDN. The distribution has been successfully built and shared in ...

The `$refs` variable in Vue can be used to reference a specific Vue component within a class-st

Would it be possible to access this.$refs.label? I am using the package vue-property-decorator. Below is the content of the component: <template> <div> <label ref="label">asd</label> </div> </template> <scr ...

Is it possible for search engines like google to index Javascript content that is stored within divs and loaded onto the page?

My website utilizes JavaScript to dynamically add content to div elements, like so: <script> //This content is generated by PHP var contents = [ "Item 1", "Item 2" ]; //Display the first item document.getElementById( "item" ).textCo ...