Way to ng-repeat defined number of times instead of repeating over array?
Here is an example of how you could do this. Note that I was inspired by a comment in the ng-repeat docs: http://jsfiddle.net/digitalzebra/wnWY6/
Note the ng-repeat directive:
<div ng-app>
<div ng-controller="TestCtrl">
<div ng-repeat="a in range(5) track by $index">{{$index + 1}}</div>
</div>
</div>
Here is the controller:
function TestCtrl($scope) {
$scope.range = function(n) {
return new Array(n);
};
};
Update (9/25/2018)
Newer versions of AngularJS (>= 1.3.0) allow you to do this with only a variable (no function needed):
<li ng-repeat="x in [].constructor(number) track by $index">
<span>{{ $index+1 }}</span>
</li>
$scope.number = 5;
This was not possible at the time the question was first asked. Credit to @Nikhil Nambiar from his answer below for this update
Original (5/29/2013)
At the moment, ng-repeat
only accepts a collection as a parameter, but you could do this:
<li ng-repeat="i in getNumber(number)">
<span>{{ $index+1 }}</span>
</li>
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.
EDIT (1/6/2014) -- Newer versions of AngularJS (>= 1.1.5) require track by $index
:
<li ng-repeat="i in getNumber(number) track by $index">
<span>{{ $index+1 }}</span>
</li>
Here is a fiddle with a couple of lists using the same getNumber
function.
I think this jsFiddle from this thread might be what you're looking for.
<div ng-app ng-controller="Main">
<div ng-repeat="item in items | limitTo:2">
{{item.name}}
</div>
</div>
you can do this:
<div ng-repeat="i in [1, 2, 3, 4]">
...
</div>