Random thoughts & observations

From the mundane to the profound and everything in between here’s what’s rocking our world

Incrementing a loop inside an angularjs view

Posted: February 14, 2015
Written by: Saints At Play
Category: AngularJS

If you've been using AngularJS for some time you might find there are occasions where you want to display the incremented value of a loop counter inside a view instead of calculating/returning that from within the controller logic.

Doing this is incredibly easy...

ng-repeat is your friend

The ng-repeat directive, used to iterate through and display items in a template, also exposes special properties that the developer can use while the loop is being processed.

One of these is the $index property which, as its name suggests, indicates the current index value of the item being iterated through.

Say for example that you wanted to assign a number to each loop item being rendered in the DOM. You could accomplish this with something akin to the following:

  <li ng-repeat="item in items">
    <span class="listing-number">{{ $index + 1 }}</span>
      // Rendered data to follow here

Thanks to Angular JS it really is as simple as that!

In case you're wondering, we add a value of one to the $index property in the above code, as arrays always start from zero.

Of course, in the controller logic you could have added a special key/value pair to the target array of data. This additional key/value pair would be used to store an incremented value for each entry in the array. This amended array could then have been iterated through in the view with the ng-repeat directive and the number displayed against each item.

The only downside with using the controller approach to incrementing numbers for each data entry is if the values have to be sorted within the view. If this happens then the numbering will be out of sync and look odd to say the least. By using the $index property of the ng-repeat directive within the view you avoid this scenario completely.

A nice and simple little technique but surprisingly efficient.

« Return to Posts


There are no comments

Posting comments after three months has been disabled.