Question: I have a list of players belonging to different teams. How can I use an Angular filter to group and display players by their teams?
Example Data:
[{name: 'Gene', team: 'alpha'}, {name: 'George', team: 'beta'}, {name: 'Steve', team: 'gamma'}, {name: 'Paula', team: 'beta'}, {name: 'Scruath', team: 'gamma'}]
Desired Result:
- team alpha - Gene - team beta - George - Paula - team gamma - Steve - Scruath
Answer: To achieve this grouping, you can utilize the groupBy filter from the angular.filter module.
JavaScript:
$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'"> <li>Group name: {{ key }}</li> <ul> <li ng-repeat="player in value"> Player: {{ player.name }} </li> </ul> </ul>
Output:
- Group name: alpha - Player: Gene - Group name: beta - Player: George - Player: Paula - Group name: gamma - Player: Steve - Player: Scruath
Note:
The above is the detailed content of How can I group and display players by their teams using Angular filters?. For more information, please follow other related articles on the PHP Chinese website!