Home >Web Front-end >JS Tutorial >How to Group Players by Team in Angular with ng-repeat?
How to Group Data in Angular with ng-repeat
In AngularJS, the built-in filter module provides a utility function called groupBy to assist with data grouping. This question addresses the need to group a list of players, each belonging to a specific team, and then display players within their respective groups.
To achieve this, the following steps can be taken:
1. Import the angular.filter Module:
As a prerequisite, the angular.filter module must be imported and added as a dependency to the application's main module.
2. Prepare the Player Data:
Create a JavaScript array containing the player data, with each player object having a name property and a team property indicating the player's team.
3. Use the groupBy Filter in Angular Template:
Within the Angular template, use the groupBy filter to group the players based on their team property. This filter accepts an expression as an argument, in this case, 'team,' to perform the grouping.
4. Iterate over Grouped Players:
Use the ng-repeat directive to iterate over the grouped players. Each iteration will provide access to a group key (i.e., the team name) and a list of players within that group.
5. Display Group and Player Information:
Within the ng-repeat iteration, display the group key (team name) and the player's name for each group.
Example Code:
<ul ng-repeat="(key, value) in players | groupBy: 'team'"> <li>Group: {{ key }} <ul> <li ng-repeat="player in value">{{ player.name }}</li> </ul> </ul>
With this approach, you can effectively group and display players based on their team affiliation.
The above is the detailed content of How to Group Players by Team in Angular with ng-repeat?. For more information, please follow other related articles on the PHP Chinese website!