Displaying Groups with AngularJS ng-repeat-start and ng-repeat-end (with Example)
- Estimated read time: 4 min read
- Written by Chad Campbell on Oct 20th 2013
Developers often need to display data in groups. Beginning with version 1.2, AngularJS provides two directives to help meet this need. Those two directives are
ng-repeat-end. Together, they complement
ng-repeat to help visually organize the data. You can see what the final result of this post will look like here.
Step 1: Get your data in order
Often, the data is exposed as properties on the view model. In the AngularJS world, the view model is represented as the
$scope object. This object can get properties attached to it in the controller. For the sake of our example, we'll setup our view model like this:
This snippet sets up the view model. This view model has a collection of teams. Each team has an id, a name, and a list of players. The next stop on our journey involves displaying each team's (group's) name.
Step 2: Display the group names
Switching focus from the view model to the view, its time to decorate our HTML. Assuming our controller code (controllers.js) is referenced, we'll attach it to the DOM using the
ng-controller directive. To display each group's name, we'll rely on the
ng-repeat directive. An example of using
ng-repeat is shown here:
This code sample uses the
ng-repeat directive to initialize a
DIV for every team in
DIV displays the team's name. To show each team's list of player's, we'll rely on the
Step 3: Display each groups data
Displaying each group's data relies on having parent/child relationships setup in your view model. In step 1 we setup those relationships. The parent in our example is a team. The children are the players on the team. Each parent represents a group. We'll build on the past snippet to list each team's players.
At this point, the data is displayed in logical groups. However, while technically correct. Visual distinction between the groups is missing. For that reason, you might want to consider how to decorate the groups.
Step 4: Decorate the groups (optional)
To visually show each team, we'll rely on some good ole CSS. As can be seen in the demo, each team name will be displayed in with a green banner. Each team's roster will be slightly indented from the left. The CSS used in this example is:
Then, the class header is added to the same
DIV element that has the
ng-repeat-start directive. The class
item is added to indent each player's name under its respective team name.
These four steps show how to display groups of data with AngularJS. If you want to see a completed example, you can view it here. The code used for this blog post can be pulled from GitHub. If you have any questions or comments related to this post, please leave them in the comments below. If you would like other help from Ecofic, please contact us.