In this post I am going to explain, how we can use ng-repeat
directive in AngularJS. This is my fourth blog in AngularJS series.
In our previous posts so far, we have worked with simple object like
var obj = { name: 'Test Controller', result: 100 };
Now lets see how can we work with array and then loop through the objects in that array. So, lets say we have a array of objects like this:-
var sites = [{ site: 'Google', rank: 1 }, { site: 'Facebook', rank: 2 }, { site: 'YouTube', rank: 3 }, { site: 'Yahoo!', rank: 4 }, { site: 'Wikipedia', rank: 7 }];
Now lets see how would be our HTML markup like after including the ng-repeat
directive.
<body ng-controller="myController as controller"> <table class="table table-hover"> <tr> <th>Rank</th> <th>Site</th> </tr> <tr ng-repeat="siteObj in controller.sites"> <td>{{siteObj.rank}}</td> <td>{{siteObj.site}}</td> </tr> </table> </body>
And our controller code in app.js
file is like this:-
(function() { var sites = [{ site: 'Google', rank: 1 }, { site: 'Facebook', rank: 2 }, { site: 'YouTube', rank: 3 }, { site: 'Yahoo!', rank: 4 }, { site: 'Wikipedia', rank: 7 }]; var app = angular.module('myModule', []); app.controller('myController', function() { this.sites = sites; }); })();
Explanation:-
In the our controller code we have declared a sites array which contains a collection of many high ranked sites with name and the search rating in the world. Next we have created a sites property inside the controller and assigned the sites array to it. In our HTML page we are using the ng-repeat
directive and using that we are calling the sites property that we had assigned to our controller and then passing each item to a user defined loop variable here it is named as siteObj
and then using the AngularJS expressions we can show each site name & rank to the users.
Demo:
Working Demo on Plunker
That’s it! If you have any comments or suggestion about this post, I would really appreciate it.
Happy Coding 🙂
Pingback: Using Forms and Models in AngularJS | jQuery Tips and Tricks