Last Updated: February 25, 2016
· joseym
Morton 066e

ngN00b: AngularJS looping $index

I've decided to start a series of protips focusing on those just beginning angular.js; I'll be calling it ngN00b.

If you're interested all items in the series will be tagged with ngN00b.

Sometimes its useful to know the index of an item as your looping thru it with the ngRepeat directive.

Say you have a method defined in your controller that will remove the item from a list, the easiest way to do this (on an array, at least) is to know the index and splice it away.

Did you know

The ngRepeat directive passes a secret variable to each item in the loop. This variable is $index.

Each item within ngRepeat is it's own scope

Each item in the ngRepeat loop is basically its own directive, with its own scope, and $index is a variable within that scope! Those tricky ngWizards!

Put up or shut up!

Take this array

$scope.arrayItems = ['Item 1', 'Item 2', 'Item 3'];

And loop thru it in a list

<ul class="list">
    <li ng-repeat="item in arrayItems">{{ $index }} - {{ item }}</li>

When we print {{ $index }} we will get the index of the item in the loop ( 0, 1, 2 respectively ).

$index is available regardless of type of loop. It comes with both arrays and objects.

This also works with hashes (or javascript objects).

$scope.objectItems = {
  'first' : 'Item 1',
  'second' : 'Item 2',
   'third' : 'Item 3'
<ul class="list">
    <li ng-repeat="item in objectItems">{{ $index }} - {{ item }}</li>

The output of this loop would be identical to the first.

Another Secret

Really none of this is a secret, but due to the fast-changing nature of the project it can be hard to sift thru some of these lower-end features when the world is blowing up about Directives and Services.

(key, val)

If you're looping thru an object $index wont provide you with the key for the object, but rather the numbered index (just like an array).

If you need to access the key you can simply set up your ngRepeat loop like so:

<ul class="list">
    <li ng-repeat="(key, val) in objectItems">{{ $index }} - {{ key }} = {{ val }}</li>

Your output would look something like this:

  • 0 - first = Item 1
  • 1 - second = Item 2
  • 2 - third = Item 3

Don't take my word for it!

Here's a fiddle as proof!

Say Thanks

1 Response
Add your response



over 1 year ago ·