use*_*240 14 angularjs ng-repeat
感谢您花时间阅读本文,我想知道如何使用ng-repeat创建一个像选项框一样的网格.我想取一个数组重复第n个项目,然后移动到下一行或列,直到列出所有项目.例如
假设我有一个像[opt1,opt2,opt3,opt4,opt5,opt6,opt7]我想要显示它的数组:
opt1 opt2 opt3
opt4 opt5 opt6
opt7
Run Code Online (Sandbox Code Playgroud)
小智 18
这比AngularJS更像是样式/标记问题.如果你真的想,你可以这样做:
<span ng:repeat="(index, value) in array">
{{value}}<br ng:show="(index+1)%3==0" />
</span>
Run Code Online (Sandbox Code Playgroud)
对不起我的HAML和Bootstrap3:
.row
.col-lg-4
%div{'ng:repeat' => "item in array.slice(0, array.length / 3)"}
{{item}}
.col-lg-4
%div{'ng:repeat' => "item in array.slice(array.length / 3, array.length * 2/3)"}
{{item}}
.col-lg-4
%div{'ng:repeat' => "item in array.slice(array.length * 2/3, array.length)"}
{{item}}
Run Code Online (Sandbox Code Playgroud)
还有另一个版本,可以使用过滤器:
<div class="row">
<div class="col-md-4" ng-repeat="remainder in [0,1,2]">
<span ng-repeat="item in array" ng-if="$index % 3 == remainder">{{item}}</span>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
如果您的所有项目都在一个阵列中,那么最好的办法是在CSS中创建一个网格.本文应该有所帮助:http://css-tricks.com/dont-overthink-it-grids/
您可以使用ng-repeat中的$ index为列应用正确的类(在本例中为4列网格):
<div class="col-{{ $index % 4 }}"></div>
Run Code Online (Sandbox Code Playgroud)
如果你有一个二维数组(分成行和列),这将开辟更多的可能性,比如实际使用HTML表.