Angular ng-repeat conditional wrap items in element (group items in ng-repeat)

懵懂的女人 提交于 2019-11-26 11:45:40

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

usage: 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:
Group name: alpha
* player: Gene
Group name: beta
* player: George
* player: Paula
Group name: gamma
* player: Steve
* player: Scruath

UPDATE: jsbin

First make group in 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 Make 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 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

Just a simple HTML solution for static groups.

<ul>
  Group name: Football
  <li ng-repeat="player in players" ng-if="player.group == 'football'">
    Player Name: {{ player.name }} 
  </li>
  Group name: Basketball
  <li ng-repeat="player in players" ng-if="player.group == 'basketball'">
    Player Name: {{ player.name }} 
  </li>
</ul>

Output:

Group name: Football
- Player Name: Nikodem
- Player Name: Lambert
Group name: Basketball
- Player Name: John
- Player Name: Izaäk
- Player Name: Dionisia

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