Using repeating elements in AngularJS
Friday 10 May 2013
- Getting started with AngularJS
- Creating an AngularJS Controller
- The AngularJS $scope is not the MVC Model
- Using repeating elements in AngularJS
- Filtering the data in an AngularJS ngRepeat element
- Using the AngularJS FormController to control form submission
- Creating an AngularJS Directive
In the previous posts I showed how to get started with AngularJS and use some of the basic AngularJS directives to data bind. In these examples I uses a really simple single element to bind to. However in lots of business cases you really need to display a list of repeating elements. Fortunately this is really easy to do.
The AngularJS ng-repeat directive
Whenever you need to repeat a specific block of HTML markup for each item in an array the ng-repeat directive is your friend. Take a look at the simple list of people below.
The data for this list is contained in an array that is added to the $scope object in the controller. The actual controller is real simple, see the code below.
The markup to generate the list in the screenshot is also real simple:
The DIV element containing the ng-repeat, and everything inside it, is simply repeated for every person in the array of people. Simple right :-)
Editing the people
Editing the people in the list is really easy, just add an input control and use the same ng-model directive as before.
In the screenshot below I am changing Jacob to Bob and as I type in the input element the text behind it is updated immediately.