ng-repeat track by $index side effect (BUG)
When using ng-repeat with track by $index option I can not delete correct element from array or object (ng-repeat will always remove the last element).
plunkr: http://plnkr.co/edit/mnw4DL7D8wn1hP7ThSD4?p=preview (the plunkr is a bit complicated, because I did not know what was causing this issue at first, clicking on green or blue square should remove it but it removes the last square - the yellow one instead!)
Using track by $id(item) works correctly.
Your problem is simply that the compiler directive is not re-compiling the element when its data attribute changes. This is solved easily by setting a $scope.$watch.
http://plnkr.co/edit/R1dujJJxLlKmw2tEkGC0?p=preview
Yes it can be solved using $watch or track by $id(item) the problem is inconsistent behaviour. The behaviour should be the same using track by $index or track by $id(item)
track by $id(example) example: http://plnkr.co/edit/aXp47fxYY7HSqcc6PDA1?p=preview
track by $indexexample: http://plnkr.co/edit/mnw4DL7D8wn1hP7ThSD4?p=preview
There is no reason that track by $id(example) and track by $index will behave the same. The first keys the elements by their value and the second keys them by their position. When you remove an item when using track by $index the ng-repeat behaves like the last element was removed and the value of the first was updated to be the value of the new first, the value of the second was updated to the value of the new second, etc. This is the expected behavior.
I think I understand now that track by $index and track by $id(item) should not behave the same (?) but the documentation on this is unclear (and there is still the problem with the example below):
From the documentation ( http://docs.angularjs.org/api/ng/directive/ngRepeat ):
item in items is equivalent to item in items track by $id(item). This implies that the DOM elements will be associated by item identity in the array.
plunkr: http://plnkr.co/edit/t16PNyBIzaDVSA4WLDcj?p=preview does not work the same as: plunkr: http://plnkr.co/edit/ruNLz9jFrMQmC0iDemmR?p=preview
item in items track by $id(item) is the default only if items is an array. For objects, the default is (key, item) in items track by key, which explains the different behavior you are seeing. I agree that this is not documented properly.
Ok, should I open an issue on angular.org? (closing this one)
hi , have problem with updating element i
Thanks!!!!