tom tom - 4 months ago 5x
AngularJS Question

Changing object inside ngRepeat

I'm iterating over an array of objects via ngRepat. Each one gets a directive. Inside that directive I'm trying to assign to the scope variable which at first works fine, but upon changing the array it gets resetted.

<test-directive obj="obj" ng-repeat="obj in objects"></test-directive>

app.directive('testDirective', function() {
return {
restrict: 'E',
scope: { obj: '=' },
template: '<div><a ng-click="doTheThing()">{{obj.title}}</a></div>',
link: function($scope, $element, $attrs) {
$scope.doTheThing = function() {
$scope.obj = { changed: true, title: 'Is changed.'};

Demo: (Click the items to apply the change, upon clicking verify which adds a new element, everything is reset).

Simply changing the attributes accordingly, instead of the whole object, won't help me, I'm actually reassigning different subclasses in my own code.


I think this is intended behavior. The ng-repeat still loops for "obj in objects", and the data will refresh at many random intervals depending on angular's cycles. Here, you can see it refreshing the data everytime you add a new item. You are not changing the "objects" data, only the local reference to the item in the objects array.

Try passing the $index via ng-repeat to the item local scope,

<a ng-click="doTheThing($index)">

Then update the data

$scope.objects[index] = { changed: true, title: 'Is changed.'};