[javascript] Iteration ng-repeat only X times in AngularJs

How can I use ng-repeat like for in Javascript?

example:

<div ng-repeat="4">Text</div>

I want to iterate with ng-repeat 4 times but how can I do it?

This question is related to javascript angularjs

The answer is


All answers here seem to assume that items is an array. However, in AngularJS, it might as well be an object. In that case, neither filtering with limitTo nor array.slice will work. As one possible solution, you can convert your object to an array, if you don't mind losing the object keys. Here is an example of a filter to do just that:

myFilter.filter('obj2arr', function() {
    return function(obj) {
        if (typeof obj === 'object') {
            var arr = [], i = 0, key;
            for( key in obj ) {
                arr[i] = obj[key];
                i++;
            }
            return arr;
        }
        else {
            return obj;
        }

    };
});

Once it is an array, use slice or limitTo, as stated in other answers.


You can use slice method in javascript array object

<div ng-repeat="item in items.slice(0, 4)">{{item}}</div>

Short n sweet


in the html :

<div ng-repeat="t in getTimes(4)">text</div>

and in the controller :

$scope.getTimes=function(n){
     return new Array(n);
};

http://plnkr.co/edit/j5kNLY4Xr43CzcjM1gkj

EDIT :

with angularjs > 1.2.x

<div ng-repeat="t in getTimes(4) track by $index">TEXT</div>

This is the simplest workaround I could think of.

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

Here's a Plunker example.


To repeat 7 times, try to use a an array with length=7, then track it by $index:

<span ng-repeat="a in (((b=[]).length=7)&&b) track by $index" ng-bind="$index + 1 + ', '"></span>

b=[] create an empty Array «b»,
.length=7 set it's size to «7»,
&&b let the new Array «b» be available to ng-repeat,
track by $index where «$index» is the position of iteration.
ng-bind="$index + 1" display starting at 1.

To repeat X times:
just replace 7 by X.


Answer given by @mpm is not working it gives the error

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}

To avoid this along with

ng-repeat="t in getTimes(4)"

use

track by $index

like this

<div ng-repeat="t in getTimes(4) track by $index">TEXT</div>