迭代 n- 仅在 AngularJs 中重复 X 次

如何在 Javascript 中使用类似于 为了的 n- 重复?

例如:

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

我想用 n- 重复4次迭代,但是我怎么做呢?

105504 次浏览

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>

You can use slice method in javascript array object

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

Short n sweet

Angular comes with a limitTo:limit filter, it support limiting first x items and last x items:

<div ng-repeat="item in items|limitTo:4">\{\{item}}</div>

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>

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.

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.

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.