longplay longplay - 1 year ago 94
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.


<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>


angular.module('myApp', [])
.controller('Ctrl', ['$scope', function ($scope) {
$scope.test = function(amount) {
var result = [];
for (var i = 0; i < amount; i++) {
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 Source

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/