我使用我的自定义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>