Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
886 views
in Technique[技术] by (71.8m points)

angularjs - Can I group by multiple fields using Angular-Filter?

I'm using Angular-Filter's groupBy filter.

Example from GitHub:

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

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

So, the example groups the players collection by team. Imagine there's an age property for every player object:

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

I want to group by team and age. How can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Follow the example of multiple fields

angular.module('app',['angular.filter'])
  .controller('MainController', function($scope) { 
    $scope.players = [
      {name: 'Gene', team: 'alpha', age: 19},
      {name: 'George', team: 'beta', age: 19},
      {name: 'Steve', team: 'gamma', age: 23},
      {name: 'Paula', team: 'beta', age: 23},
      {name: 'Scruath', team: 'gamma', age: 23}
    ];
 });
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
  
<meta name="description" content="[groupBy example]"/>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div ng-controller="MainController"> 

<ul ng-repeat="(key, value) in players | groupBy: '[team,age]'">
  <b>Group name: {{key}}</b>
  <br>
  <li ng-repeat="player in value">
    <b>player:</b> {{ player.name }} 
    <br>
    <b>team:</b> {{player.team}} 
    <br>
    <span ng-if="player.age"><b>age:</b> {{ player.age }}</span>
  </li>
</ul>
  </div>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...