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>
Angular-JS ng-repeat directive is a handy tool to repeat a set of HTML code for a number of times or once per item in a collection of items. ng-repeat is mostly used on arrays and objects.
Definition and Usage The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.
The ng-repeat-start directive works the same as ng-repeat, but will repeat all the HTML code (including the tag it's defined on) up to and including the ending HTML tag where ng-repeat-end is placed.
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
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.
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