Table of contents

< Previous chapterNext chapter >

Last updated .

Displaying collections with ng-repeat

Being able to display single data values and to keep the data in sync with the view is nice. But how do we handle collections of data? That kind of data should go in a list of some sort, like an unordered list or table. The Angular ng-repeat directive is for precisely this purpose. To experiment with this, I modified the controller to expose an array of objects; in this example the number of items is fixed, but imagine a collection of arbitrary length in the real world. The app.js script file now contains this:

( function () { var app = angular.module('AngularProject', []); app.controller("myController", MyController); function MyController() { var vm = this; // Array of Contact objects vm.Contacts = [ { Name: "Albert Einstein", Email: "" }, { Name: "Niels Bohr", Email: "" }, { Name: "Stephen Hawking", Email: "" }, ]; } } )();

Then, I changed the template (i.e. the html) to make use of the ng-repeat construct inside a html table. Now, each object in the array is supposed to be displayed in a table row:

<!doctype html> <html ng-app="AngularProject"> <head> <title>Home</title> <meta charset="utf-8" /> <script src="Scripts/Angular/angular-1.5.0-rc.0/angular.js"></script> </head> <body ng-controller="myController as vm"> <table> <thead><tr><td>Name</td><td>Email</td></tr></thead> <tbody> <tr ng-repeat="contact in vm.Contacts"> <td>{{ contact.Name }}</td><td>{{ contact.Email }}</td> </tr> </tbody> </table> <script src="Scripts/App.js"></script> </body> </html>
The view: A table of three contacts
The view: A table of three contacts

That ng-repeat syntax looks conspicuously similar to a Razor @foreach block, I think. And no wonder - they serve the same purpose: to output a collection of data to the document. In this case, the vm.Contacts collection is iterated, producing one row per item. The name "contact" represents the current object in the iteration and it could be anything, but it is just a good habit to use a name suggestive of what the object actually is. Notice that ng-repeat is set on the tr element; in a html list it would be on a li element.

The ng-repeat directive is quite versatile, it allows one to filter and sort the collection on the fly and to format the output, among other things.

New stuff

ng-repeat: The ngRepeat directive instantiates a template (the html element) once per item from a collection. Use it to make lists or tables from collections of data.

< Previous chapterNext : Filtering, ordering and formatting >

2016 by Niels Hede Pedersen Linked in