I know I can use ng-repeat
to iterate over collections. How do I iterate over a range. For example, something like:
<div class='aoeu' ng-repeat='count in range(1,5)'>
<div id='{{count}}'></div>
</div>
There is no range() function in Javascript, but you can create a function that returns an array of values that suits your needs, or use a JS library for that effect. I would use underscore.js, very simply:
<div class='aoeu' ng-repeat='count in _.range(1,5)'>
<div id='{{count}}'></div>
</div>
Of course, for you to be able to use underscore in your angular app (in directives, and such), you need to include it in your scopes. Include underscore.js in your project, and in your main controller do $rootScope._ = _
This way, any controller or directive in angular recognizes a $scope._ (that references the underscore library), and the above snippet will work! (if all you will ever need is to create arbitrary ranges, you can make the range function yourself - and by 'make' I mean copying any of the million available examples available.. Here's one)
Underscore seems to be the most expressive, but you might want to look at this answer: AngularJS ng-options create range
It uses a filter to create an array. Here's my version
var App = angular.module('app', []);
App.filter('range', function() {
return function(arr, lower, upper) {
for (var i = lower; i <= upper; i++){
arr.push(i);
}
return arr;
};
});
Which you would use like:
<li ng-repeat="n in [] | range:5:10"> {{n}} </li>
And the JSFiddle http://jsfiddle.net/jaimem/hKvNc/4/
pd: if you prefer parseInt
to converting strings to integers don't forget to pass the radix
. In the answer I linked is missing when parsing min
and max
.