如何使用Angular过滤器对元素进行分组?

时间:2017-03-27 11:26:35

标签: javascript angularjs angular-filters

enter image description here

我在分组相同ID

的元素时遇到问题
<ul ng-repeat="(key, value) in players | groupBy: 'team'">
  Group name: {{ key }}
 <li ng-repeat="player in value">
  player: {{ player.name }} 
 </li>

js code:

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

我收到错误this type

  

错误:$ injector:unpr   未知的提供商   未知提供商:groupByFilterProvider <- groupByFilter

2 个答案:

答案 0 :(得分:1)

groupBy并非由Angular提供的过滤器构建,您可以使用angular.filter模块,它可以为您提供许多过滤器,如groupBy,flatten,filterBy,pluck等。

//added angular.filter module after adding its reference
angular.module('myApp', ['angular.filter']); 

Here您可以找到内置过滤器列表

答案 1 :(得分:0)

编写特定功能以对数据进行分组:

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

  var indexedTeams = [];

  $scope.playersToFilter = function() {
    indexedTeams = [];
    return $scope.players;
  }

  $scope.filterTeams = function(player) {
    var teamIsNew = indexedTeams.indexOf(player.team) == -1;
    if (teamIsNew) {
      indexedTeams.push(player.team);
    }
    return teamIsNew;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="Main">
  <div ng-repeat="p in playersToFilter() | filter:filterTeams">
    <b>{{p.team}}</b>
    <li ng-repeat="player in players | filter:{team: p.team}">{{player.name}}</li>
  </div>
</div>