本文共 2775 字,大约阅读时间需要 9 分钟。
本文翻译自:
Is there a way to ng-repeat a defined number of times instead of always having to iterate over an array? 有没有办法重复定义的次数而不是总是迭代一个数组?
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 例如,下面我希望列表项显示5次,假设$scope.number
等于5另外增加数字,所以每个列表项增量如1,2,3,4,5
Desired result: 期望的结果:
参考:
At the moment, ng-repeat
only accepts a collection as a parameter, but you could do this: 目前, ng-repeat
只接受一个集合作为参数,但你可以这样做:
And somewhere in your controller: 在控制器的某个地方:
$scope.number = 5;$scope.getNumber = function(num) { return new Array(num); }
This would allow you to change $scope.number
to any number as you please and still maintain the binding you're looking for. 这将允许您根据需要将$scope.number
更改$scope.number
任意数字,并仍然保持您正在寻找的绑定。
with a couple of lists using the same getNumber
function. 使用相同getNumber
函数的几个列表 。
EDIT 1/6/2014 : Newer versions of Angular 1.x make use of the following syntax: 编辑2014年1月6日 :较新版本的Angular 1.x使用以下语法:
EDIT 9/25/2018 : Newer versions of Angular 1.x allow you to do this without a function. 编辑9/25/2018 :较新版本的Angular 1.x允许您在没有功能的情况下执行此操作。 If your code is simple and you don't need a getNumber
function for other reasons, you can now omit that and just do this: 如果您的代码很简单,并且由于其他原因您不需要getNumber
函数,那么您现在可以省略它并执行此操作:
Credit to @Nikhil Nambiar from his answer below for this update 感谢@Nikhil Nambiar从他的回答中获得此更新
I think this from this might be what you're looking for. 我觉得这个从这个可能是你在找什么。
{ {item.name}}
Here is an example of how you could do this. 这是一个如何做到这一点的例子。 Note that I was inspired by a comment in the ng-repeat docs: 请注意,我受到ng-repeat文档中的评论的启发: :
Note the ng-repeat directive: 注意ng-repeat指令:
{ {$index + 1}}
Here is the controller: 这是控制器:
function TestCtrl($scope) { $scope.range = function(n) { return new Array(n); };};
I needed a more dynamic solution to this - where I could increment the repeat. 我需要一个更动态的解决方案 - 我可以增加重复。
HTML HTML
Duplicator Control 复制器控制
Create another user with the same permissions
JS JS
$scope.newUserCount = Array('1');var primaryValue = 1;$scope.duplicateUser = function(){ primaryValue++; $scope.newUserCount.push(primaryValue)}
You can use this example. 您可以使用此示例。
Inside controller: 内控制器:
$scope.data = { 'myVal': 33, 'maxVal': 55, 'indexCount': function(count) { var cnt = 10; if (typeof count === 'number') { cnt = count; } return new Array(cnt); }};
Example for select element at the HTML code side: HTML代码侧的select元素示例:
转载地址:http://nbexb.baihongyu.com/