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总是喜欢毫无理由地重新评估它们,如果你像我这样有成千上万个过滤器,这将是一个巨大的瓶颈。
这个指令甚至会监视模型中的变化,并相应地更新元素。
我提出了一个稍微不同的语法,它更适合我一点,并添加了一个可选的下界:
myApp.filter('makeRange', function() {
return function(input) {
var lowBound, highBound;
switch (input.length) {
case 1:
lowBound = 0;
highBound = parseInt(input[0]) - 1;
break;
case 2:
lowBound = parseInt(input[0]);
highBound = parseInt(input[1]);
break;
default:
return input;
}
var result = [];
for (var i = lowBound; i <= highBound; i++)
result.push(i);
return result;
};
});
你可以用哪个
<div ng-repeat="n in [10] | makeRange">Do something 0..9: {{n}}</div>
or
<div ng-repeat="n in [20, 29] | makeRange">Do something 20..29: {{n}}</div>
我使用自定义ng-repeat-range指令:
/**
* Ng-Repeat implementation working with number ranges.
*
* @author Umed Khudoiberdiev
*/
angular.module('commonsMain').directive('ngRepeatRange', ['$compile', function ($compile) {
return {
replace: true,
scope: { from: '=', to: '=', step: '=' },
link: function (scope, element, attrs) {
// returns an array with the range of numbers
// you can use _.range instead if you use underscore
function range(from, to, step) {
var array = [];
while (from + step <= to)
array[array.length] = from += step;
return array;
}
// prepare range options
var from = scope.from || 0;
var step = scope.step || 1;
var to = scope.to || attrs.ngRepeatRange;
// get range of numbers, convert to the string and add ng-repeat
var rangeString = range(from, to + 1, step).join(',');
angular.element(element).attr('ng-repeat', 'n in [' + rangeString + ']');
angular.element(element).removeAttr('ng-repeat-range');
$compile(element)(scope);
}
};
}]);
HTML代码是
<div ng-repeat-range from="0" to="20" step="5">
Hello 4 times!
</div>
或者简单地
<div ng-repeat-range from="5" to="10">
Hello 5 times!
</div>
或者简单地说
<div ng-repeat-range to="3">
Hello 3 times!
</div>
或者只是
<div ng-repeat-range="7">
Hello 7 times!
</div>