Malcr001 Malcr001 - 3 months ago 16
AngularJS Question

Way to ng-repeat defined number of times instead of repeating over array?

Is there a way to ng-repeat a defined number of times instead of always having to iterate over an array?

For example, below I want the list item to show up 5 times assuming

$scope.number
equal to 5 in addition incrementing the number so each list item increments like 1, 2, 3, 4, 5

Desired result:

<ul>
<li><span>1</span></li>
<li><span>2</span></li>
<li><span>3</span></li>
<li><span>4</span></li>
<li><span>5</span></li>
</ul>

Answer

At the moment, ng-repeat only accepts a collection as a parameter, but you could do this:

<ul>
    <li ng-repeat="i in getNumber(number)"><span>{{$index+1}}</span></li>
</ul>

And somewhere in your controller:

$scope.number = 5;
$scope.getNumber = function(num) {
    return new Array(num);   
}

This would allow you to change $scope.number to any number as you please and still maintain the binding you're looking for.

Here is a fiddle with a couple of lists using the same getNumber function.

EDIT 1/6/2014: Newer versions of Angular make use of the following syntax:

<li ng-repeat="i in getNumber(number) track by $index">