Home  >  Article  >  Web Front-end  >  How can I group and display players by their teams using Angular filters?

How can I group and display players by their teams using Angular filters?

DDD
DDDOriginal
2024-11-18 04:07:02196browse

How can I group and display players by their teams using Angular filters?

Grouping Data with Angular Filters

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:

  • Remember to include angular.filter in your module's dependencies.
  • For more information on angular.filter, refer to external resources such as jsbin.com.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn