Angular确实在HTML指令中提供了一些使用数字的for循环的支持:

<div data-ng-repeat="i in [1,2,3,4,5]">
  do something
</div>

但是,如果作用域变量包含一个具有动态数字的范围,那么每次都需要创建一个空数组。

在控制器中

var range = [];
for(var i=0;i<total;i++) {
  range.push(i);
}
$scope.range = range;

在HTML中

<div data-ng-repeat="i in range">
  do something
</div>

这是可行的,但这是不必要的,因为我们在循环中根本不会使用范围数组。有人知道设置最小/最大值的范围或规则吗?

喜欢的东西:

<div data-ng-repeat="i in 1 .. 100">
  do something
</div>

当前回答

我做了这个,觉得它可能对一些人有用。(是的,CoffeeScript。起诉我。)

指令

app.directive 'times', ->
  link: (scope, element, attrs) ->
    repeater = element.html()
    scope.$watch attrs.times, (value) ->
      element.html ''
      return unless value?
      element.html Array(value + 1).join(repeater)

使用方法:

HTML

<div times="customer.conversations_count">
  <i class="icon-picture></i>
</div>

还能再简单一点吗?

我对过滤器很谨慎,因为Angular总是喜欢毫无理由地重新评估它们,如果你像我这样有成千上万个过滤器,这将是一个巨大的瓶颈。

这个指令甚至会监视模型中的变化,并相应地更新元素。

其他回答

假设美元范围。referncerl是一个数组

for(var i=0; i<$scope.refernceurl.length; i++){
    $scope.urls+=$scope.refernceurl[i].link+",";
}

只有简单的Javascript(你甚至不需要一个控制器):

<div ng-repeat="n in [].constructor(10) track by $index">
    {{ $index }}
</div>

在模拟时非常有用

最简单的无代码解决方案是初始化一个数组的范围,并使用$index +无论多少我想通过偏移:

<select ng-init="(_Array = []).length = 5;">
    <option ng-repeat="i in _Array track by $index">{{$index+5}}</option>
</select>

我稍微调整了一下这个答案,然后想出了这个小提琴。

过滤器定义为:

var myApp = angular.module('myApp', []);
myApp.filter('range', function() {
  return function(input, total) {
    total = parseInt(total);

    for (var i=0; i<total; i++) {
      input.push(i);
    }

    return input;
  };
});

像这样重复使用:

<div ng-repeat="n in [] | range:100">
  do something
</div>

这是最简单的变体: 只需使用整数数组....

< lig repeat= < n >测试: