Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicates not allowed error in ng-repeat when list of objects in an array

I am confused why ng-repeat is giving me duplicates error. I can solve it using track by $index but I want to know when this error is thrown by angular.

This is clear

<div ng-repeat="a in [1,1,1,1]">...</div>

As there are duplicates value in above array, it will definitely throw an Dups error.

What about list of objects

<div ng-repeat="a in items">...</div>

JS

$scope.items = [
                   {"ab":1,"bc":3},
                   {"ab":1,"bc":3}
               ]

How does angular treats/compare second one to decide whether there are duplicate values or not?

Thanks.

EDIT

Why I am not getting duplication error?

Fiddle DEMO

like image 693
Jay Shukla Avatar asked Mar 21 '23 07:03

Jay Shukla


1 Answers

See this tutorial http://www.anujgakhar.com/2013/06/15/duplicates-in-a-repeater-are-not-allowed-in-angularjs/ .

In your case, because your two objects have the same key values (ab) you get the error. Adding a track by $index might solve the problem.

EDIT

From the source code.

variable in expression track by tracking_expression` – You can also provide an optional tracking function * which can be used to associate the objects in the collection with the DOM elements. If no tracking function * is specified the ng-repeat associates elements by identity in the collection. It is an error to have * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression, * before specifying a tracking expression.

As I understand it, two elements in the repeat resolve to the same tracking id ($$hashkey I believe) you will get the error. You should really check out their source code. It's pretty well commented and annotated.

like image 150
NicolasMoise Avatar answered Apr 08 '23 21:04

NicolasMoise