如何使用AngularJS ng-repeat
显示以下HTML(Twitter Bootstrap Scaffolding)?基本上,每隔三条记录我需要关闭</div>
,打印<hr>
,然后打开另一条<div class="span4">
<div class="row">
<div class="span4">
<h3>
Project A
</h3>
</div>
<div class="span4">
<h3>
Project B
</h3>
</div>
<div class="span4">
<h3>
Project C
</h3>
</div>
</div>
<hr>
<div class="row">
<div class="span4">
<h3>
Project D
</h3>
</div>
<div class="span4">
<h3>
Lab Title
</h3>
</div>
<div class="span4">
<h3>
Project E
</h3>
</div>
</div>
我为代码演示创建了一个小提琴 http://jsfiddle.net/ADukg/261/
答案 0 :(得分:38)
这是一种方式:
<div ng-controller="MyCtrl">
<div ng-repeat="project in projects">
<span ng-if="$index % 3 == 0">
<hr />
<div class="row">
<h3 class="span4" ng-if="projects[$index+0]">{{projects[$index+0]}}</h3>
<h3 class="span4" ng-if="projects[$index+1]">{{projects[$index+1]}}</h3>
<h3 class="span4" ng-if="projects[$index+2]">{{projects[$index+2]}}</h3>
</div>
</span>
</div>
</div>
如果您有7个数据项,这种方式也可以使用:在最后3个数据中,它只显示第7项,而不是尝试显示不存在的项目8和9。
编辑:已更新为使用ng-if&amp;角度1.2.12
答案 1 :(得分:16)
继续the more easy answer。我不喜欢原始的解决方案,因为它产生了空的dom元素。这是每行3个div。
<div ng-controller="ModulesCtrl">
<div class="row" ng-repeat="i in fields.range()">
<div class="span4" ng-repeat="field in fields.slice(i,i+3)">
<h2>{{field}}</h2>
</div>
</div>
</div>
在函数FieldsCtrl($ scope)中:
$scope.fields.range = function() {
var range = [];
for( var i = 0; i < $scope.fields.length; i = i + 3 )
range.push(i);
return range;
}
如果你知道fields.length你可以代替fields.range()使用[0,3,6,9]等
答案 2 :(得分:15)
更优雅的方法是使用视图模型提供分块集合,然后让视图处理它像
<div ng-controller="Controller">
Projects <input ng-model="projects"></input>
<hr/>
<div ng-repeat="row in rows">
<div ng-repeat="project in row">
Projects {{project}}
</div>
<hr/>
</div>
</div>
并且coffeescript非常简单
# Break up an array into even sized chunks.
chunk = (a,s)->
if a.length == 0
[]
else
( a[i..i+s-1] for i in [0..a.length - 1 ] by s)
@Controller = ($scope)->
$scope.projects = "ABCDEF"
$scope.$watch "projects", ->
$scope.rows = chunk $scope.projects.split(""), 3
angular.bootstrap(document, []);
答案 3 :(得分:2)
要使视图逻辑远离控制器并具有更可重用的解决方案,您可以创建一个自定义过滤器,将阵列拆分为行组:
angular.module('app').filter('group', function() {
/**
* splits an array into groups of the given size
* e.g. ([1, 2, 3, 4, 5], 2) -> [[1, 2], [3, 4], [5]]
*/
return function(array, groupSize) {
return _.groupBy(array, function(val, index) {
return Math.floor(index / groupSize);
});
};
});
在视图中:
<div class="row" ng-repeat="group in projects | group:3">
<div class="span4" ng-repeat="project in group">
{{project}}
</div>
</div>
要包含小时,您可以使用ng-repeat起点和终点:
<div class="row" ng-repeat-start="group in projects | group:3">
<div class="span4" ng-repeat="project in group">
{{project}}
</div>
</div>
<hr ng-repeat-end />
答案 4 :(得分:2)
ng-repeat-start and ng-repeat-end end points似乎是实现这一目标的便捷方式:
这导致简单的代码
<div ng-controller="MyCtrl">
<div ng-repeat-start="project in projects">
<span>
<div class="row">
<h3 class="span4">{{project}}</h3>
</div
</span>
</div>
<hr ng-repeat-end ng-if="($index + 1) % 3 == 0" />
</div>
请参阅此jsfiddle