Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-repeat, for-loop and push

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?

like image 914
longplay Avatar asked Apr 19 '16 11:04

longplay


3 Answers

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/

like image 110
potatopeelings Avatar answered Nov 07 '22 19:11

potatopeelings


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.

like image 33
Khalid Hussain Avatar answered Nov 07 '22 18:11

Khalid Hussain


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

like image 40
Rajeev Jayaswal Avatar answered Nov 07 '22 17:11

Rajeev Jayaswal