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>
I ran into the same issue. I came across this thread, but didn't like the methods they had here. My solution was using underscore.js, which we had already installed. It's as simple as this:
This will do exactly what you're looking for.
Easiest answer: 2 lines of code
JS (in your AngularJS controller)
HTML
...where
repeatCount
is the number of repetitions that should appear in this location.Heres an answer for angular 1.2.x
Basically it is the same, with the slight modification of of the
ng-repeat
here is the fiddle: http://jsfiddle.net/cHQLH/153/
this is because angular 1.2 doesn't allow duplicate values in the directive. This means if you are trying to do the following, you will get an error.
Angular provides filters to modify a collection. In this case the collection would be null, i.e. [], and the filter also takes arguments, as follows:
JS:
This method is very similar to those proposed above and isn't necessarily superior but shows the power of filters in AngularJS.
At the moment,
ng-repeat
only accepts a collection as a parameter, but you could do this:And somewhere in your controller:
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 1.x make use of the following syntax:
EDIT 9/25/2018: Newer versions of Angular 1.x allow you to do this without a function. If your code is simple and you don't need a
getNumber
function for other reasons, you can now omit that and just do this:Credit to @Nikhil Nambiar from his answer below for this update
First, create an angular filter using LoDash:
The LoDash times function is capable of handling null, undefined, 0, numbers, and string representation of numbers.
Then, use it in your HTML as this:
or