是否有一种方法可以ng-repeat定义的次数,而不是总是要迭代一个数组?

例如,下面我希望列表项显示5次,假设为$scope。数字等于5,加上增加的数字,所以每个列表项都增加,如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>

当前回答

$scope.number = 5;

<div ng-repeat="n in [] | range:$scope.number">
      <span>{{$index}}</span>
</div>

其他回答

我需要一个更动态的解决方案-我可以增加重复。

超文本标记语言

<div ng-repeat="n in newUserCount">
<input type="text" value="" name="newuser{{n}}"/>
</div>

复印机控制

<span class="helper" ng-click="duplicateUser()">
Create another user with the same permissions
</span>

JS

 $scope.newUserCount = Array('1');
var primaryValue = 1;
$scope.duplicateUser = function()
{
    primaryValue++;
    $scope.newUserCount.push(primaryValue)
}

下面是一个如何做到这一点的例子。请注意,我的灵感来自ng-repeat文档中的一个注释:http://jsfiddle.net/digitalzebra/wnWY6/

注意ng-repeat指令:

<div ng-app>
    <div ng-controller="TestCtrl">
        <div ng-repeat="a in range(5) track by $index">{{$index + 1}}</div>
    </div>
</div>

这是控制器:

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

最简单的答案:2行代码

JS(在你的AngularJS控制器中)

$scope.range = new Array(MAX_REPEATS); // set MAX_REPEATS to the most repetitions you will ever need in a single ng-repeat that makes use of this strategy

HTML

<div ng-repeat="i in range.slice(0,repeatCount) track by $index"></div>

...其中repeatCount是应该出现在该位置的重复次数。

你可以使用ng-if指令和ng-repeat

因此,如果num是元素需要重复的次数:

<li ng-repeat="item in list" ng-if="$index < num">

我也遇到了同样的问题。我偶然发现了这条线索,但不喜欢他们在这里的方法。我的解决方案是使用我们已经安装好的underscore.js。其实很简单:

<ul>
    <li ng-repeat="n in _.range(1,6)"><span>{{n}}</span></li>
</ul>

这正是你想要的。