What is the angularjs way to databind many inputs?

The reason that databinding to a primitive “item” doesn’t work is because of the way ng-repeat creates the child scopes for each item. For each item, ng-repeat has the new child scope prototypically inherit from the parent scope (see dashed lines in picture below), and then it assigns the item’s value to a new property on the child scope (red items in picture below). The name of the new property is the loop variable’s name. From the ng-repeat source code:

childScope = scope.$new();
...
childScope[valueIdent] = value;

If item is a primitive, the new child scope property is essentially assigned a copy of the primitive’s value. This child scope property is not visible to the parent scope, and changes you make to the input field are stored in this child scope property. E.g., suppose we have in the parent scope

$scope.list = [ 'value 1', 'value 2', 'value 3' ];

And in the HTML:

<div ng-repeat="item in list">

Then, the first child scope would have the following item property, with a primitive value (value 1):

item: "value 1"

ng-repeat with primitives

Because of the ng-model databinding, changes you make to the form’s input field are stored in that child scope property.

You can verify this by logging the child scope to the console. Add to your HTML, inside the ng-repeat:

<a ng-click="showScope($event)">show scope</a>

Add to your controller:

$scope.showScope = function(e) {
    console.log(angular.element(e.srcElement).scope());
}


With @Gloopy’s approach, each child scope still gets a new “item” property, but because list is now an array of objects, childScope[valueIdent] = value; results in the item property’s value being set to a reference to one of the array objects (not a copy).

ng-repeat with objects

Using the showScope() technique, you’ll see that the child scope item property’s value references one of the array objects — it is no longer a primitive value.

See also don’t bind to primitives in ng-repeat child scopes and
What are the nuances of scope prototypal / prototypical inheritance in AngularJS? (which contains pictures of what the scopes look like when using ng-repeat).

Leave a Comment