Elements of the ng-repeat group

I have an array of items elements.

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

I would like items=['a', 'b', 'c', 'd', 'e', 'f', 'g'] be displayed in groups of 3, which will display 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 supports circumventing this. Does it have? If not, how would you do it?

Thanks in advance.

+6
source share
3 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

+12
source

AFAIK there are no grouping directives in angular.

The solution is to group the data (underscore.js is suitable for this) and then nested ng repeats in the view.

+1
source

You can define your own filter:

 app.filter('inGroupsOf', function() { var memoized = {}; return function() { key = Array.prototype.slice.call(arguments); if (typeof memoized[key] === "undefined") { memoized[key] = _inGroupsOf.apply(this, arguments); } return memoized[key]; }; function _inGroupsOf(collection, group_size) { var ar = []; var i, j; for (i = 0, j = -1; i < collection.length; i++) { if (i % group_size == 0) { j++; ar[j] = []; } ar[j].push(collection[i]); } return ar; } }); 

It uses memoization to prevent Error: 10 $digest() iterations reached. Aborting! Error: 10 $digest() iterations reached. Aborting!

0
source

Source: https://habr.com/ru/post/955637/


All Articles