问题描述
有没有办法ng-repeat
指定次数而不是总是迭代数组?
Is there a way to ng-repeat
a defined number of times instead of always having to iterate over an array?
例如,在下面假设 $scope.number
等于 5 的情况下,我希望列表项显示 5 次,另外增加数字,这样每个列表项都会增加 1、2、3、4, 5
For example, below I want the list item to show up 5 times assuming $scope.number
equal to 5 in addition incrementing the number so each list item increments like 1, 2, 3, 4, 5
预期结果:
<ul>
<li><span>1</span></li>
<li><span>2</span></li>
<li><span>3</span></li>
<li><span>4</span></li>
<li><span>5</span></li>
</ul>
推荐答案
更新 (9/25/2018)
较新版本的 AngularJS (>= 1.3.0) 允许您仅使用一个变量(不需要函数)来执行此操作:
Update (9/25/2018)
Newer versions of AngularJS (>= 1.3.0) allow you to do this with only a variable (no function needed):
<li ng-repeat="x in [].constructor(number) track by $index">
<span>{{ $index+1 }}</span>
</li>
$scope.number = 5;
在第一次提出问题时,这是不可能的.感谢@Nikhil Nambiar 对此更新的回答
This was not possible at the time the question was first asked. Credit to @Nikhil Nambiar from his answer below for this update
目前,ng-repeat
只接受一个集合作为参数,但你可以这样做:
At the moment, ng-repeat
only accepts a collection as a parameter, but you could do this:
<li ng-repeat="i in getNumber(number)">
<span>{{ $index+1 }}</span>
</li>
在你的控制器中的某个地方:
And somewhere in your controller:
$scope.number = 5;
$scope.getNumber = function(num) {
return new Array(num);
}
这将允许您根据需要将 $scope.number
更改为任何数字,并且仍然保持您正在寻找的绑定.
This would allow you to change $scope.number
to any number as you please and still maintain the binding you're looking for.
EDIT (1/6/2014) -- 较新版本的 AngularJS (>= 1.1.5) 需要 track by $index
:
EDIT (1/6/2014) -- Newer versions of AngularJS (>= 1.1.5) require track by $index
:
<li ng-repeat="i in getNumber(number) track by $index">
<span>{{ $index+1 }}</span>
</li>
Here is a fiddle 有几个列表使用相同的 getNumber
功能.
Here is a fiddle with a couple of lists using the same getNumber
function.
这篇关于ng-repeat 定义的次数而不是重复数组的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!