如何使用角度过滤器对数据进行分组?
我有一个属于每个小组的球员名单。如何使用过滤器列出每个组的用户?
[{name: 'Gene', team: 'team alpha'},
{name: 'George', team: 'team beta'},
{name: 'Steve', team: 'team gamma'},
{name: 'Paula', team: 'team beta'},
{name: 'Scruath of the 5th sector', team: 'team gamma'}];
我在寻找这个结果:
- team alpha
- Gene
- team beta
- George
- Paula
- team gamma
- Steve
- Scruath of the 5th sector
-
可以使用angular.filter模块的groupBy。 因此您可以执行以下操作:
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>
结果:
Group name: alpha * player: Gene
Group name: beta * player: George * player: Paula
Group name: gamma * player: Steve * player: Scruath更新:
jsbin请记住要使用的基本要求angular.filter
,特别注意您必须将其添加到模块的依赖项中:(1)您可以使用4种不同的方法安装角度过滤器:
- 克隆并构建此存储库
- 通过Bower:通过运行$ bower在终端上安装angular-filter
- 通过npm:通过运行$ npm从您的终端安装angular-filter
- 通过cdnjs
filter
(2)在包含Angular本身之后,在您的index.html中包含angular-filter.js(或angular-filter.min.js)。
(3)将“ angular.filter”添加到主模块的依赖项列表中。