Intro to Ng-repeat Track by $index

Recently, I set out to create a Javascript application using Angular, a framework with which I had (and still have) extremely limited experience using. The main feature of the application required the incorporation of what was essentially nested to-do lists. Hours turned into days as I tried to figured out how to make this work, but only when I discovered the useful ?track by $index? Ng-repeat feature was I able to make my nested to-do list dreams come true.

When using Ng-repeat with the ?track by $index? feature, it allows you, as you may have guessed, to keep track of the indexes of the array that are being iterated over. This is extremely useful when you have an array of objects and you need to access properties within those objects. In the case of my application, a travel planner, I was able to save an array of objects that had a property for the names of the cities as well as a nested array inside with attractions in those cities. Using ?track by $index? I was able to iterate through the main objects array, and then access the attractions array inside each object.

By accessing the index, I was also able to create simple functions that take in the index as a parameter to easily manipulate each object.

Below are two examples I used in my code, the first shows how I used ng-repeat to iterate through the main array and the second shows how I was able to use the $index to iterate through the inner array.

<div class=”cityDiv” ng-repeat=”city in cities track by $index”>

and

<li style=”list-style: none;”, ng-repeat=”x in cities[$index].attractions track by $index”>{{city.attractions[$index]}}</li>

By using $index as a function parameter, I was able to create a button that accessed the inner arrays of my city objects. Here is an example:

<button class=”clear” ng-click=”deleteCity($index)”>Delete City</button>

*Pro tip* Another useful feature I discovered using ?track by $index? is that I was able to make duplicates within the arrays, whereas I was receiving ?dupe? errors that would break my app when adding multiple items of the same name.

14

No Responses

Write a response