longplay longplay - 7 months ago 26
Javascript Question

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?

Answer

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/