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

当前回答

2021年的版本

*ngFor="let x of [].constructor(number)"

其他回答

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

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

你可以用这个例子。

在控制器:

$scope.data = {
    'myVal': 33,
    'maxVal': 55,
    'indexCount': function(count) {
        var cnt = 10;
        if (typeof count === 'number') {
            cnt = count;
        }
        return new Array(cnt);
    }
};

在HTML代码端选择元素的例子:

<select ng-model="data.myVal" value="{{ data.myVal }}">
    <option ng-repeat="i in data.indexCount(data.maxVal) track by $index" value="{{ $index + 1 }}">{{ $index + 1 }}</option>
</select>

对于使用CoffeeScript的用户,您可以使用范围理解:

指令

link: (scope, element, attrs) ->
  scope.range = [1..+attrs.range]

或控制器

$scope.range = [1..+$someVariable]
$scope.range = [1..5] # Or just an integer

模板

<div ng-repeat="i in range">[ the rest of your code ]</div>
$scope.number = 5;

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

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

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

生活的例子

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