Angular ng-repeat conditional wrapping elements in an element (group elements in ng-repeat)

I am trying to group elements into ng-repeat using a condition.

An example is the combination of all elements with the same hour.

Data:

[ {name: 'AAA', time: '12:05'}, {name: 'BBB', time: '12:10'}, {name: 'CCC', time: '13:20'}, {name: 'DDD', time: '13:30'}, {name: 'EEE', time: '13:40'}, ... ] 

The time field is actually a timestamp (1399372207), but with the exact time, the output of the example is easier to understand.

I list these elements using ng-repeat:

 <div ng-repeat="r in data| orderBy:sort:direction"> <p>{{r.name}}</p> </div> 

also tried:

 <div ng-repeat-start="r in data| orderBy:sort:direction"></div> <p>{{r.name}}</p> <div ng-repeat-end></div> 

Valid is:

 <div class="group-class"> <div><p>AAA</p></div> <div><p>BBB</p></div> </div> <div class="group-class"> <div><p>CCC</p></div> <div><p>DDD</p></div> <div><p>EEE</p></div> </div> 

My last option, if there is no easy solution for my problem, is to group the data and then assign it to the variable of the region used in ng-repeat.

Any thoughts?

+48
angularjs angularjs-ng-repeat ng-repeat
May 6 '14 at 11:09
source share
2 answers

You can use the groupBy filter of angular.filter module.
so you can do something like this:

use: collection | groupBy:property collection | groupBy:property
use nested property with dot notation: property.nested_property
JS:

 $scope.players = [ {name: 'Gene', team: 'alpha'}, {name: 'George', team: 'beta'}, {name: 'Steve', team: 'gamma'}, {name: 'Paula', team: 'beta'}, {name: 'Scruath', team: 'gamma'} ]; 

HTML:

 <ul ng-repeat="(key, value) in players | groupBy: 'team'"> Group name: {{ key }} <li ng-repeat="player in value"> player: {{ player.name }} </li> </ul> 

RESULT:
Band Name: alpha
* player: Gene
Band Name: Beta
* player: George
* player: Paula
Band Name: gamma
* player: Steve
* player: Scruath

UPDATE: jsbin

+126
Aug 16 '14 at 17:54 on
source share

First create a group in the controller:

  $scope.getGroups = function () { var groupArray = []; angular.forEach($scope.data, function (item, idx) { if (groupArray.indexOf(parseInt(item.time)) == -1) { groupArray.push(parseInt(item.time)); } }); return groupArray.sort(); }; 

Then create a filter for it:

  myApp.filter('groupby', function(){ return function(items,group){ return items.filter(function(element, index, array) { return parseInt(element.time)==group; }); } }) ; 

Then change the template:

  <div ng-repeat='group in getGroups()'> <div ng-repeat="r in data | groupby:group" class="group-class"> <div><p>{{r.name}}</p></div> </div> </div> 

SEE DEMO

+14
May 6 '14 at 11:45
source share



All Articles