【发布时间】:2014-11-20 03:25:47
【问题描述】:
我正在尝试使用 ng-repeat 创建两列。我有一个项目列表,即 ['green', 'red', 'blue', 'yellow'] 并想创建两列,每列有两个项目。但是,如果当前索引为 mod 2,我不确定如何开始新行。
green red
blue yellow
有没有办法做到这一点?
【问题讨论】:
标签: html angularjs angularjs-ng-repeat
我正在尝试使用 ng-repeat 创建两列。我有一个项目列表,即 ['green', 'red', 'blue', 'yellow'] 并想创建两列,每列有两个项目。但是,如果当前索引为 mod 2,我不确定如何开始新行。
green red
blue yellow
有没有办法做到这一点?
【问题讨论】:
标签: html angularjs angularjs-ng-repeat
我只是在将数据传递给 DOM 之前准备好数据,你可以在网上找到很多“块”实现
['green', 'red', 'blue', 'yellow']
split into suitable chunks:
[ [ "green", "red" ], [ "blue", "yellow" ] ]
代码:
<div data-ng-controller="MyCtrl">
<table>
<tr data-ng-repeat="row in tableData">
<td data-ng-repeat="color in row">
{{ color }}
</td>
</tr>
</table>
</div>
<script>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.colors = ['green', 'red', 'blue', 'yellow'];
$scope.tableData = chunk($scope.colors, 2);
}
function chunk (arr, len) {
var chunks = [],
i = 0,
n = arr.length;
while (i < n) {
chunks.push(arr.slice(i, i += len));
}
return chunks;
}
</script>
输出
green red
blue yellow
【讨论】:
你可以通过css控制它
如果您使用的是引导程序
<div class="row">
<div data-ng-repeat="color in colors" class="col-md-6"> {{ color }} </div>
</div>
如果您不使用引导程序,您可以在 CSS 中设置一个宽度为 50% 的类,然后将该类添加到 div 中。像这样的
CSS
.width-50 {
width: 50%;
}
HTML
<div data-ng-repeat="color in colors" class="width-50"> {{ color }} </div>
【讨论】: