Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
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 5 at 17:33
2  
Duplicate of: stackoverflow.com/questions/16296670/… –  MichaelOryl Feb 5 at 17:41

3 Answers 3

up vote 5 down vote accepted

For this case, you want track by $index

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

explanation from docs:

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

share|improve this answer

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

share|improve this answer
    
You removed the duplicates from your code, so you're not even addressing the issue. –  ImNotMike Feb 6 at 9:22

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.