4

It took me a long time to debug where the fault was when I was trying to list some stuff from a database. It turns out that if there are values in an array that are duplicates, Angular refuses to use the array at all in ng-repeat.

An example of which can be found here: http://jsfiddle.net/2uyxu7ha/

Javascript:

var app = angular.module("Module", []);
app.controller("Controller", function($scope){
    $scope.array1 = ["1", "2", "3", "4"];
    $scope.array2 = ["1", "1", "3", "4"];
});

HTML:

<div ng-app="Module">
    <div ng-controller="Controller as ctrl">
        <ul>
            <li ng-repeat="item in array1">{{item}}</li>
        </ul>
        <ul>
            <li ng-repeat="item in array2">{{item}}</li>
        </ul>
    </div>
</div>

As you will notice, there is just one value that repeats in the second array, and the whole list is therefore not displayed. If you just change the second value to "2", it will be displayed.

I don't want this behavior, because even if there are some repeating values in the database, I still want to see them on the front-end. Why does this happen and how do I fix it?

Michael Oryl
  • 20,856
  • 14
  • 77
  • 117
Digital Ninja
  • 3,415
  • 5
  • 26
  • 51
  • 1
    The error message makes it pretty clear: `Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: item in array2, Duplicate key: string:1` – Mark Feb 05 '15 at 17:33
  • 2
    Duplicate of: http://stackoverflow.com/questions/16296670/angular-ng-repeat-error-duplicates-in-a-repeater-are-not-allowed/17246507 – Michael Oryl Feb 05 '15 at 17:41

3 Answers3

5

For this case, you want track by $index

http://jsfiddle.net/2uyxu7ha/1/

explanation from docs:

https://docs.angularjs.org/error/ngRepeat/dupes

haimlit
  • 2,572
  • 2
  • 22
  • 26
0

You need to use track by $index at the end of your ng-repeat

Oam Psy
  • 8,555
  • 32
  • 93
  • 157
0

Since you're using the ControllerAs syntax, you can just reference $scope in your controller using this, and in your HTML you just have to make sure you reference the right array.

See updated fiddle:

[http://jsfiddle.net/jaykan24/2uyxu7ha/2/][1]

Now you don't have to worry about duplicate ngRepeat issues. Hopefully this can help

JayKan
  • 3,966
  • 2
  • 20
  • 21