Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS For Loop with Numbers & Ranges

I tweaked this answer a bit and came up with this fiddle.

Filter defined as:

var myApp = angular.module('myApp', []);
myApp.filter('range', function() {
  return function(input, total) {
    total = parseInt(total);

    for (var i=0; i<total; i++) {
      input.push(i);
    }

    return input;
  };
});

With the repeat used like this:

<div ng-repeat="n in [] | range:100">
  do something
</div>

I came up with an even simpler version, for creating a range between two defined numbers, eg. 5 to 15

See demo on JSFiddle

HTML:

<ul>
    <li ng-repeat="n in range(5,15)">Number {{n}}</li>
</ul>

Controller:

$scope.range = function(min, max, step) {
    step = step || 1;
    var input = [];
    for (var i = min; i <= max; i += step) {
        input.push(i);
    }
    return input;
};

Nothing but plain Javascript (you don't even need a controller):

<div ng-repeat="n in [].constructor(10) track by $index">
    {{ $index }}
</div>

Very useful when mockuping


I came up with a slightly different syntax which suits me a little bit more and adds an optional lower bound as well:

myApp.filter('makeRange', function() {
        return function(input) {
            var lowBound, highBound;
            switch (input.length) {
            case 1:
                lowBound = 0;
                highBound = parseInt(input[0]) - 1;
                break;
            case 2:
                lowBound = parseInt(input[0]);
                highBound = parseInt(input[1]);
                break;
            default:
                return input;
            }
            var result = [];
            for (var i = lowBound; i <= highBound; i++)
                result.push(i);
            return result;
        };
    });

which you can use as

<div ng-repeat="n in [10] | makeRange">Do something 0..9: {{n}}</div>

or

<div ng-repeat="n in [20, 29] | makeRange">Do something 20..29: {{n}}</div>

For those new to angularjs. The index can be gotten by using $index.

For example:

<div ng-repeat="n in [] | range:10">
    do something number {{$index}}
</div>

Which will, when you're using Gloopy's handy filter, print:
do something number 0
do something number 1
do something number 2
do something number 3
do something number 4
do something number 5
do something number 6
do something number 7
do something number 8
do something number 9