Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group ng-repeat items

I have an array of items items.

I would like to use the ng-repeat directive or something similar, to group n 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>
<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>
<div class="row">
   <div class="col-sm-4">g</div>
</div>

I know I could do some processing to turn items into 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.

like image 928
Patrick Lorio Avatar asked Oct 10 '13 00:10

Patrick Lorio


People also ask

What is ng-repeat?

Definition and Usage The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

How do I group data in Angularjs?

To group data, users can drag and drop column headers onto and from the area above the grid. This area is called the groupPanel. Set its visible property to true to show it. Users can reorder headers within the groupPanel to change group hierarchy.

What is ng options?

Definition and UsageThe ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.


2 Answers

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>
                </div>
            </span>
        </span>
    </div>
</div>

Demo: http://bootply.com/86855

like image 154
Zim Avatar answered Sep 29 '22 01:09

Zim


AFAIK there is no grouping directives in angular.

A solution is to group the data (underscore.js is good for this) and then have nested ng-repeats in the view.

like image 22
Anton Avatar answered Sep 29 '22 00:09

Anton