The ng-model binding does not automatically update another ng-model within the same object

Check out this code snippet:

http://plnkr.co/edit/aycnNVoD96UMbsC7rFmg?p=preview

<div data-ng-app="" data-ng-init="names=['One']">

<input type="text" ng-model="names[0]">

  <p>Using ng-repeat to loop:</p>
  <ul>
    <li data-ng-repeat="name in names">
      <input type="text" ng-model="name"> {{ name }}
    </li>
  </ul>

</div>

When I update the value of names[0] in the first input field, it updates the values of the second input field as well. However, when I update the value of names[0] in the second input field, it does not affect the first input field. Why is that?

Answer №1

To make it function properly, ensure that your second input is bound to names[$index]

<input type="text" ng-model="names[$index]"> {{ name }}

Answer №2

One reason for this behavior is the use of ng-repeat, which creates a child scope. As a result, the reference to the "name" variable inside the ng-repeat differs from the original one in the names array. More information can be found here:

It's important to note that ng-repeat, ng-switch, ng-view, and ng-include all generate new child scopes, leading to issues when working with these directives. (For a quick demonstration, check out this .)

The reason behind this phenomenon is that by binding the input to the "name" variable within the ng-repeat, a new property called "name" is created on the child scope established by the directive. This causes the ng-model of the textbox created by the ng-repeat to refer to a different "name" compared to the actual first element of the names array. To prevent this, it is recommended to utilize names[$index] to implicitly refer to the first element of the names array without creating a new "name" property on the child scope. Binding ng-models to objects rather than primitives is considered a best practice in Angular development, as mentioned by Sandy in their response. Additionally, using $index to access the first element of the names array can help resolve this issue, as highlighted by other contributors. Understanding scope inheritance nuances in Angular is crucial; more insights can be found here.

For additional resources, check out:

This link and this one.

Answer №3

Sharing my thoughts on this topic, which is somewhat related to the issue at hand.

<body>
<div data-ng-app="" data-ng-init="names=[{value:'One'}, {value:'Two'}]">
  <p>Utilizing ng-repeat for looping:</p>
  <ul>
    <li data-ng-repeat="name in names">
      <input type="text" ng-model="name.value"> {{ name }}
    </li>
  </ul>
</div>
</body>

Instead of directly binding the array item to the control, I prefer creating an object for each array and then binding the value of each item. This approach helps avoid reference issues.

Check out a functional demo here on jsfiddle

I hope this information proves useful.

Answer №4

Ensure that you include $index within your ng-model.

<li data-ng-repeat="name in names">
    <input type="text" ng-model="names[$index]"> {{ name }}
</li>

Currently, you have assigned ng-model="names[0]", indicating that the value is bound to the first index of the names array.

By using ng-model="names[$index]" in ng-repeat, each value will be bound accordingly in the array. $index serves as an iterator offset for the repeated element.

names[0] = 'One'
names[1] = 'Two'

And so forth!

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

The concealed [hidden] attribute in Angular2 triggers the display of the element after a brief delay

I am currently utilizing the [hidden] attribute within my application to conceal certain elements based on a specific condition. The situation is such that I have two divs - one for displaying results and another for showing the text "No results". Both t ...

Unable to get $scope.$on to function correctly within Jasmine SpecRunner

Recently, I've delved into using Jasmine to test an AngularJS application. I'm fairly confident that I've imported all the necessary components in the SpecRunner file, but I keep encountering this error: TypeError: $scope.$on is not a funct ...

Is it possible to link the _id of a mongodb array to its corresponding clientId in another array?

I am facing a challenge with 2 arrays retrieved from my MongoDB database. The first array is called users and it contains user objects structured like this: [{ email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a1beb ...

Utilizing Typescript for parsing large JSON files

I have encountered an issue while trying to parse/process a large 25 MB JSON file using Typescript. It seems that the code I have written is taking too long (and sometimes even timing out). I am not sure why this is happening or if there is a more efficien ...

Error 405: Javascript page redirection leads to Method Not Allowed issue

After receiving the result from the ajax success method, I am facing an issue where the redirection to another page is being blocked and displaying the following error: Page 405 Method Not Allowed I am seeking suggestions on how to fix this as I need to ...

How to open a print preview in a new tab using Angular 4

Currently, I am attempting to implement print functionality in Angular 4. My goal is to have the print preview automatically open in a new tab along with the print popup window. I'm struggling to find a way to pass data from the parent window to the c ...

Content obscuring dropdown menu

I am currently working on a screen design that resembles the following: return ( <SafeAreaView> <View style={styles.container}> <View style={styles.topContainer}> <View style={styles.searchFieldContainer}> ...

Including a label for an array within an unnamed array in a JSON string

Is there a way to transform the following data: [{"name": "Donald"}, {"name": "George"}] Into this format instead: {MyArray: [{"name": "Donald"}, {"name": "George"}]} I am currently working on a database server that I built using node.js, express, an ...

Dormant versus dynamic PHP MySQL operations

I am facing an issue where the state doesn't change from active to inactive or vice versa when I click on it. Below is my code for ajax: <script src="//code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript"> ...

What is causing this iframe ads code to so severely disrupt the functionality of Internet Explorer when using document.write

So, I've recently encountered an issue where a certain problem arose, and although I managed to fix it, I am still curious about the root cause behind why it occurred in the first place. TL;DR The use of Google-provided conversion tracking code that ...

Error message stating: "Node.js 'readline' - Mark-compacts near heap limit are not effective. Allocation failed."

Here's the process I'm following in the code: Primarily, I am engaging in web scraping tasks. I start by reading a text file containing approximately 3500 links. Next, I iterate through each link, filter out the ones I need, and make a request ...

Creating a personalized confirmation function using JavaScript

Here is a function I've created to generate a confirmation box. The issue I'm facing is that the function doesn't wait for the user to click before returning true/false based on the onclick events. So, how can I solve this? function Confi ...

AngularJS - development of a service entity

After deliberating between posting in the Angular mailing list or seeking assistance from the JavaScript community, I have decided that this is more of a JavaScript question. Hopefully, the knowledgeable individuals on Stack Overflow can provide a quicker ...

To search for specific data in a Mongoose schema by specifying an attribute of type ObjectId

Here are the schemas I am working with: UserLike const UserLikeSchema = Schema({ user: { type: Schema.Types.ObjectId, ref: "User", required: [true, "User is required"], }, game: { type: Schema.Types.ObjectId, ...

The system has encountered an issue: "EntityMetadataNotFound: Unable to locate metadata for the entity named 'User

Just wanted to reach out as I've been encountering an issue with my ExpressJS app recently. A few days ago, everything was running smoothly without any errors. However, now I'm getting a frustrating EntityMetadataNotFound: No metadata for "User" ...

Console.log is not visible to jQuery's getJSON function

Currently, I am utilizing the getJSON method as shown below: $.getJSON("js/production-data.json").done(function(response) { console.log(response); console.log('hello'); }); While monitoring Firebug, the data retrieval process seems to ...

Utilize PHP SVG images to trigger internal JavaScript code through the <img> tag

Here is a php function that generates an SVG image. public function actionJsTest() { header('Content-Type: image/svg+xml'); $svg = ''; $svg .= '<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/ ...

A guide on accessing a dynamic object key in array.map()

How can I dynamically return an object key in array.map()? Currently, I am retrieving the maximum value from an array using a specific object key with the following code: Math.max.apply(Math, class.map(function (o) { return o.Students; })); In this code ...

Are there any downsides to utilizing the jQuery Load function?

I am in the process of creating a website that displays sensor data. I plan to incorporate a HighChart line chart to showcase this data. Since my website is relatively simple in terms of content, I have decided to consolidate all elements onto one page inc ...

Show a virtual numeric keypad on the HTML input fields when they are set as type text specifically for mobile devices in a unique situation

When accessing the following web page from a mobile device, I currently have number input fields with comma separators added. However, in order to implement the comma separation function, I had to set the input type to text. This resulted in showing an alp ...