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

当前回答

最简单的答案: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是应该出现在该位置的重复次数。

其他回答

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

(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>

生活的例子

我使用了下划线的时间函数,因为我们已经在项目中使用它,但你可以很容易地用本地代码替换它。

下面是一个如何做到这一点的例子。请注意,我的灵感来自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);
    };
};

Angular提供了过滤器来修改集合。在这种情况下,集合将为空,即[],过滤器也接受参数,如下所示:

<div id="demo">
    <ul>
        <li ng-repeat="not in []|fixedNumber:number track by $index">{{$index}}</li>
    </ul>
</div>

JS:

module.filter('fixedNumber', function() {
    return function(emptyarray, number) {
        return Array(number);
    }
});

module.controller('myCtrl', ['$scope', function($scope) {
    $scope.number = 5;
}]);

这个方法与上面提出的方法非常相似,不一定更优秀,但显示了AngularJS中过滤器的强大功能。

首先,使用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>

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

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

这正是你想要的。