是否有一种方法可以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>

当前回答

我也遇到过同样的问题,这就是我得出的结论:

(function () {
  angular
    .module('app')
    .directive('repeatTimes', repeatTimes);

  function repeatTimes ($window, $compile) {
    return { link: link };

    function link (scope, element, attrs) {
      var times    = scope.$eval(attrs.repeatTimes),
          template = element.clone().removeAttr('repeat-times');

      $window._(times).times(function (i) {
        var _scope = angular.extend(scope.$new(), { '$index': i });
        var html = $compile(template.clone())(_scope);

        html.insertBefore(element);
      });

      element.remove();
    }
  }
})();

... 和html:

<div repeat-times="4">{{ $index }}</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)
}

首先,使用LoDash创建一个角过滤器:

angular.module('myApp').filter('times', function(){
   return function(value){
      return _.times(value || 0);
   }
});

LoDash times函数能够处理null, undefined, 0,数字和数字的字符串表示。

然后,在你的HTML中像这样使用它:

<span ng-repeat="i in 5 | times">
 <!--DO STUFF-->
</span>

or

<span ng-repeat="i in myVar | times">
 <!--DO STUFF-->
</span>

我认为这个jsFiddle从这个线程可能是你正在寻找的。

<div ng-app ng-controller="Main">
   <div ng-repeat="item in items | limitTo:2">
       {{item.name}}
   </div>
</div>

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

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

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

这真的很丑,但它可以在没有控制器的情况下为整数或变量工作:

整数:

<span ng-repeat="_ in ((_ = []) && (_.length=33) && _) track by $index">{{$index}}</span>

变量:

<span ng-repeat="_ in ((_ = []) && (_.length=myVar) && _) track by $index">{{$index}}</span>