Search code examples
javascriptangularjsangularjs-ng-repeat

How to access index in a component called in ng-repeat in angularjs?


I have the following files. This is code in node-list.html

<tbody sv-node-list-item ng-repeat="item in items" />

And this is code in node-list-item.html.

<tr><td>{{$index}}</td></tr>

Basically node-list-item is rendered for each iteration of the ng-repeat of the node-list.html file. I need to access the index of the item from the parent i.e. node-list.html in node-list-item.html I have been researching this for quiet some time but am not able to do so. Please help. I am using angular1 i.e. angularjs. This is the directive code in node-list-item.js

function directive() { return { templateUrl: "partials/node-list-item.html" };}
module.directive("svNodeListItem",[ directive ]);

Solution

  • Use this in the node-list.html:(You need to send index to the node-list-item directive)

    <tbody ng-repeat="item in items track by $index" sv-node-list-item index="{{$index}}"/>
    

    Then change your sv-node-list-item directive to this:

    function directive() { 
        return { 
            scope: {
               index: '@'
            },
            templateUrl: "partials/node-list-item.html" 
        };
    }
    module.directive("svNodeListItem",[ directive ]);
    

    And finally your node-list-item.html to this:

    <tr><td>{{index}}</td></tr>
    

    For more information about ng-repeat check the documentation here and for directive variables here.