Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 813
Malcr001 Avatar asked May 29 '13 22:05

Malcr001


People also ask

Why we use ng-repeat in Angularjs?

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.

What is ng-repeat explain with example?

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.

What is ng-repeat end?

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.


1 Answers

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.

like image 173
Dan Avatar answered Sep 18 '22 15:09

Dan