If it isn’t already, the ngRepeat directive will soon be your favorite AngularJS tool. ngRepeat coupled with AngularJS’s sweet sweet filter function (more on that in another post) lets you kick ass and take names…well at least when it comes to iterating and displaying your models with HTML.
What Is It Again?
ngRepeat is an AngularJS directive. If you don’t know what that is, don’t worry you’ll survive the rest of this post because all you need to know is that ngRepeat saves you work when displaying things like tables, lists, or any other collection of objects that live in the business logic of your app.
For example, say we have an app that needs to display the names, stats, and fantasy point totals for all the MLB batters in 2012–also known as the app that will help Chris slay all others in his league this year:
Lets prune away the sortable columns and other widgets; and then write out only the first two player rows in plain HTML:
Nothing scary there. It’s just static HTML showing point totals, players’ names, field positions, slugging percentages, on-base percentages, team images and abbreviations.
Using this data we can now go back to the static HTML and using curly brackets tell AngularJS that we want to create data-bindings between our players’ data and HTML which was formerly static, but which we are now using as a HTML template.
You can see that the structure of the HTML is indeed the same and we have only replaced the static data with data-bindings, which AngularJS will manage and update if and when the players array is updated.
The final step is for us to use ngRepeat so we can remove the duplication we currently have in our table and also to remove the constraint that we need to know the size of the players array (since we are accessing it manually rather than iterating through it). If you are familiar with ruby blocks or other templating languages, then this last jump is easy:
There are a few other bits of AngularJS magic happening above as well. I am using the number filter to format the numerical data entries and the ngSrc directive to display the team images. You can find out more about the number filter and ngSrc in the official documentation.
Wait–I’m Still Lost
I also recommend you sign up for email updates from All Angular for more tutorials and tips. To subscribe for updates scroll up to the top of the site, enter your email, and hit the “Get Updates!” button. After that feel free to give yourself or your cat a high-five.