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?
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/
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With