是否有一种方法可以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>
我也遇到过同样的问题,这就是我得出的结论:
(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>
生活的例子
我使用了下划线的时间函数,因为我们已经在项目中使用它,但你可以很容易地用本地代码替换它。
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>