ng-repeat directive repeats the HTML elements. Let us see this with the help of an example.
Write the following HTML mark up in the webpage.
- <!doctype html>
- <html ng-app>
- <head>
- <title>My Angular App</title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
- </head>
- <body>
- <div ng-app="" ng-init="cities=['New Delhi','Mumbai','Pune']">
- <ul>
- <li ng-repeat="x in cities">
- {{ x }}
- </li>
- </ul>
- </div>
- </body>
- </html>
In the ng-init directive we defined a collection of cities. We want to display these cities as output. To do this we have taken an unordered list. Inside that we we have taken a list item. Now define the ng-repeat directive in the li tag. It is just like a for loop. It will traverse all the elements present in the collection and display them as output.
So let us check the output of the program.
![output]()
Let us try one more example that deals with an array of objects. Write the below code in the webpage.
- <!doctype html>
- <html ng-app>
- <head>
- <title>My Angular App</title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
- </head>
- <body>
- <div ng-app="" ng-init="data=[
- {State:'Maharashtra',city:'Mumbai'},
- {State:'Goa',city:'Panjim'},
- {State:'Karnataka',city:'Bengaluru'}]">
-
- <ul>
- <li ng-repeat="x in data">
- {{ x.State + ', ' + x.city }}
- </li>
- </ul>
-
- </div>
- </body>
- </html>
In this example we have defined states with cities. Ng-init directive has an array of these objects. We will display the State along with their cities using Angular JS. Using ng-repeat we will concatenate the state with the cities and display them in a comma separated format.
Let us check the output now.
![output]()
This is how ng-repeat works in Angular JS.