iterate over chunks of an array using ng-repeat

被刻印的时光 ゝ 提交于 2019-11-29 12:01:47

There isn't an existing way to do what you are saying with a table. The easiest way to do what you want is to use divs with fixed widths, so that they will auto-wrap after three.

Here is an example:

HTML

<div ng-app="app">
    <div ng-controller="TableCtrl" class="my-table">
        <span ng-repeat="person in people" class="person">{{person}}</span>
    </div>
</div>

CSS

.my-table{
    width: 400px;
    height: 400px;
    border: 1px solid black;
}

.person{
    width: 100px;
    display: inline-block;
    white-space: nowrap;
    border: 1px solid black;
}

JavaScript

var app = angular.module('app',[]);
app.controller('TableCtrl', function($scope){

    $scope.people = ['Aaron', 'Abraham', 'Adam', 'Aristotel', 'Aziel', 'Azod', 'Azood'];

});

Working copy: http://jsfiddle.net/ZX43D/

After years of angular experience, It's obvious that the best way to do this is to split the array into chunks in the controller. Each time the original array is modified, update the chunked array.

Here is my current solution (It's O(N^2) so doesn't scale for large lists).

Template:

<div ng-app="myapp">
    <div ng-controller="testing">
        <div ng-repeat="_ in items">
            <span ng-show="($parent.$index % 3 == 0) && ($parent.$index + 3 > $index) && ($parent.$index <= $index)" ng-repeat="item in items">
                <span ng-show="1">
                    {{item}}
                </span>
            </span>
        </div>
    </div>
</div>

Controller:

angular.module('myapp', []);

function testing($scope){
    $scope.items = ['a', 'b', 'c', 'd','e','f','g'];
}

Result:

a b c
d e f
g

Fiddle:

http://jsfiddle.net/LjX3m/

Conclusion:

I'll probably try use CSS for this as @aaronfrost mentions. (However it may not be possible since some wrapping divs may be required for each chunk).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!