5

I'm getting crazy. What's wrong this hello-worldesque example? I'm trying just to test some basic things with angularjs 1.5.5.

HTML:

<div ng-app="myApp" ng-controller="Ctrl">
     <h3>test 1:</h3>
     <span ng-repeat="label in test(1)">{{label}}</span>
     <h3>test 2:</h3>
     <span ng-repeat="label in test(2)">{{label}}</span>
</div>

JS:

angular.module('myApp', [])
    .controller('Ctrl', ['$scope', function ($scope) {
    $scope.test = function(amount) {
      var result = [];
      result.push("1");
      for (var i = 0; i < amount; i++) {
        result.push("2");
      }
      result.push("3");
      return result;
    }    
}]);

JsFiddle: http://jsfiddle.net/d3v6vq7w/7/

Simpy put, the loop works with 1 iterations, but not with for example 2. Nothing gets printed. What gives?

longplay
  • 61
  • 3
  • 1
    using ng-repeat with an array that is a result from a function, doesn't work well. More info here: http://stackoverflow.com/questions/12336897/how-to-loop-through-items-returned-by-a-function-with-ng-repeat – fikkatra Apr 19 '16 at 11:26
  • You should have open your console first before posting here. It was a simple duplicate error. – M. Junaid Salaat Apr 19 '16 at 11:31
  • Correct, but I didn't realize jsfiddle works that way. – longplay Apr 19 '16 at 12:04

3 Answers3

4

You have duplicates in the array you return. Adding a track by $index will solve your problem.

<span ng-repeat="label in test(2) track by $index">{{label}}</span>

Fiddle - http://jsfiddle.net/ayay0d6u/

potatopeelings
  • 40,709
  • 7
  • 95
  • 119
3

If you have a look at the error message, you will get the answer.

Error: ngRepeat:dupes Duplicate Key in Repeater Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: label in test(2), Duplicate key: string:2, Duplicate value: 2

From error page

Duplicate keys are banned because AngularJS uses keys to associate DOM nodes with items.

Khalid Hussain
  • 1,675
  • 17
  • 25
1

That's because duplicates in a repeater are not allowed. Use 'track by' expression to resolve this issue.

In your example, test2 returns [1,2,2,3] which is having duplicate element.

The example above can be resolved by using track by $index.

You can refer angular js documentation: https://docs.angularjs.org/error/ngRepeat/dupes

Rajeev Jayaswal
  • 1,423
  • 1
  • 20
  • 22