Modifying Objects Within Angular Scope Inside Ng-repeat
I'm creating a form in HTML using ng-repeat to generate the form elements from an object in the scope. I also use that object to generate other elements outside of the ng-repeat.
Solution 1:
ng-repeat
creates a child scope for each repeated item. As a result you are trying to pass a primitive to child scope which won't create a reference to parent. When you pass objects however, you pass the original object reference.
From the mouth of one of the fathers of Angular:
Always have a dot in ng-model
This is a great video regarding Angular Best Practices given by Angular creator (2012/12/11). Go to minute 31 for well explained detail of this exact situation
Modify data to array of objects:
$scope.test = [{ val:"abc",key:'a'}, {val:"def",key:'b'} ]
Then in repeater:
<formng-repeat="item in test"><label>{{item.key}}</label><inputng-model="item.val" /><p>{{item.val}}</p></form>
Solution 2:
try this:
angular.module('App', []);
function Ctrl($scope) {
$scope.test = [
{label:"a", value:"abc"},
{label:"b", value:"def"}
]
}
and
<divng-app="App"><divng-controller="Ctrl"><divclass="block1"><formng-repeat="o in test"><label>{{o.label}}</label><inputng-model="o.value" /><p>{{o.value}}</p></form></div><divclass="block2"><p>
{{test[0].value}}
</p><p>
{{test[1].value}}
</p></div></div></div>
Angularjs uses the fact that objects are passed by reference. So, if you pass a object to a function and change the object inside the function, the object outside also changes. Look at this updated JSFiddle
Post a Comment for "Modifying Objects Within Angular Scope Inside Ng-repeat"