3

So I have made this very simple script to isolate the problem. I tested with different versions of angular and in the fiddle if you select version 1.1.1 it works fine. You can hit the add button as many times as you want. Newer versions seem to have a problem with this approach. Is this a bug, a security measure or should I just write a directive? In this fiddle I am loading the latest version, but you can remove this version and change this to 1.1.1 and it will work. Also, 1.2.1 has the same problem. Thanks in advance for any tips.

HTML

<div ng-app="app"> <div ng-controller="ctrl"> <div ng-repeat="item in naam"> <div>{{item}}</div> </div> <button ng-click="add()">add</button> </div> </div> 

JS

var app = angular.module("app", []); app.controller("ctrl", function ($scope) { $scope.naam = [ "1", "2"]; $scope.add = function () { var x = 3; var y = 4; $scope.naam.push(x, y); } }); 

1 Answer 1

5

No, it's not a bug of Angular. Actually, you got an error, Error: [ngRepeat:dupes] because it's trying to add the same key into the array and the ng-repeat doesn't allow it.

So, you have to use track by as following:

 <div ng-repeat="item in naam track by $index"> <div>{{item}}</div> </div> 

Here is an upadated JSFiddle.

Sign up to request clarification or add additional context in comments.

7 Comments

Ok thanks! I was so confused of why this happened since older version did allow this. So let me understand: the index is used to repeat the values instead of the values itself. Am I right?
Yes, it's correct. FYI, the reason that your code does work on an older version, 1.1.1, and doesn't on the newer version because since AngularJS 1.2.x, it doesn't allow duplicate keys in repeaters anymore.
@LVarayut Interesting. What is the behavior of the $id() function mentioned in NgRepeat API (v. higher than 1.2.x)? For example: item in items is equivalent to item in items track by $id(item). ?docs.angularjs.org/api/ng/directive/ngRepeat
@klode Honestly, I have never used $id() but I think so. Basically, Angular automatically adds $$hashkey to each element in the ng-repeat in order to track them using the added $$hashkey. So, if you write track by $id(item), this also tells Angular to track by $$hashkey again. Logically, it is equivalent. You can take a look at this Video for more understanding and look at this JsFiddle.
Thanks @LVarayut ! So if ng-repeat=item in [1, 4, 4] the last two elements 4 will be assigned the same identical $$hashKey therefore resulting in duplicate error?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.