0

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 ]);
rexroxm
  • 868
  • 1
  • 9
  • 26

1 Answers1

1

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.

rexroxm
  • 868
  • 1
  • 9
  • 26
Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
  • trbody and tr are not part of the same file. I wouldn't have this problem if they were. I am using this node-list-item.html component at 5 or six other places where i need the same index from the parent that has ng-repeat. And node-list-item happens to be a 200 line code which i cannot put separately at all those places – rexroxm Sep 16 '19 at 09:29
  • @rexroxm the sv-node-list-item is a directive right? can you put your javascript code please? – Ricardo Rocha Sep 16 '19 at 10:21
  • yes it is a directive. it attaches node-list-item for each iteration. – rexroxm Sep 16 '19 at 10:28
  • @rexroxm ok. But can you add the code from the directive to the question so I could help you better? – Ricardo Rocha Sep 16 '19 at 13:26
  • I added directive code if there is any more stuff that needs to be added please do tell. – rexroxm Sep 17 '19 at 06:15
  • @rexroxm I mad changes the answer. Please, check out the differences and see if solves your problem. :D – Ricardo Rocha Sep 17 '19 at 09:00