Patrick Lorio Patrick Lorio - 2 years ago 110
AngularJS Question

Group ng-repeat items

I have an array of items


I would like to use the ng-repeat directive or something similar, to group
items together. For instance:

I would like
items=['a', 'b', 'c', 'd', 'e', 'f', 'g']
to be rendered in groups of 3 to be rendered as:

<div class="row">
<div class="col-sm-4">a</div>
<div class="col-sm-4">b</div>
<div class="col-sm-4">c</div>
<div class="row">
<div class="col-sm-4">d</div>
<div class="col-sm-4">e</div>
<div class="col-sm-4">f</div>
<div class="row">
<div class="col-sm-4">g</div>

I know I could do some processing to turn
items=[['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]
however I was wondering if anuglarjs had support to get around this. Does it? If not, how would you go about doing this?

Thanks in advance.

Answer Source

You can use `ng-repeat' like this..

<div ng-controller="MyCtrl">
    <div ng-repeat="item in items">
        <span ng-switch on="$index % 3">
            <span ng-switch-when="0">
                <div class="row">
                    <div class="col-sm-4" ng-show="items[$index+0]">{{items[$index+0]}}</div>
                    <div class="col-sm-4" ng-show="items[$index+1]">{{items[$index+1]}}</div>
                    <div class="col-sm-4" ng-show="items[$index+2]">{{items[$index+2]}}</div>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download