Angular does provide some support for a for loop using numbers within its HTML directives:
do something
<
Very simple one:
$scope.totalPages = new Array(10);
<div id="pagination">
<a ng-repeat="i in totalPages track by $index">
{{$index+1}}
</a>
</div>
I whipped this up and saw it might be useful for some. (Yes, CoffeeScript. Sue me.)
app.directive 'times', ->
link: (scope, element, attrs) ->
repeater = element.html()
scope.$watch attrs.times, (value) ->
element.html ''
return unless value?
element.html Array(value + 1).join(repeater)
To use:
<div times="customer.conversations_count">
<i class="icon-picture></i>
</div>
Can this get any simpler?
I'm wary about filters because Angular likes to re-evaluate them for no good reason all the time, and it's a huge bottleneck if you have thousands of them like I do.
This directive will even watch for changes in your model, and update the element accordingly.
Late to the party. But i ended up just doing this:
In your controller:
$scope.repeater = function (range) {
var arr = [];
for (var i = 0; i < range; i++) {
arr.push(i);
}
return arr;
}
Html:
<select ng-model="myRange">
<option>3</option>
<option>5</option>
</select>
<div ng-repeat="i in repeater(myRange)"></div>
Using UnderscoreJS:
angular.module('myModule')
.run(['$rootScope', function($rootScope) { $rootScope.range = _.range; }]);
Applying this to $rootScope
makes it available everywhere:
<div ng-repeat="x in range(1,10)">
{{x}}
</div>
An improvement to @Mormegil's solution
app.filter('makeRange', function() {
return function(inp) {
var range = [+inp[1] && +inp[0] || 0, +inp[1] || +inp[0]];
var min = Math.min(range[0], range[1]);
var max = Math.max(range[0], range[1]);
var result = [];
for (var i = min; i <= max; i++) result.push(i);
if (range[0] > range[1]) result.reverse();
return result;
};
});
usage
<span ng-repeat="n in [3, -3] | makeRange" ng-bind="n"></span>
3 2 1 0 -1 -2 -3
<span ng-repeat="n in [-3, 3] | makeRange" ng-bind="n"></span>
-3 -2 -1 0 1 2 3
<span ng-repeat="n in [3] | makeRange" ng-bind="n"></span>
0 1 2 3
<span ng-repeat="n in [-3] | makeRange" ng-bind="n"></span>
0 -1 -2 -3
This is jzm's improved answer (i cannot comment else i would comment her/his answer because s/he included errors). The function has a start/end range value, so it's more flexible, and... it works. This particular case is for day of month:
$scope.rangeCreator = function (minVal, maxVal) {
var arr = [];
for (var i = minVal; i <= maxVal; i++) {
arr.push(i);
}
return arr;
};
<div class="col-sm-1">
<select ng-model="monthDays">
<option ng-repeat="day in rangeCreator(1,31)">{{day}}</option>
</select>
</div>