So I have an ng-repeat nested within another ng-repeat in order to build a nav menu. On each <li>
on the inner ng-repeat loop I set an ng-click which calls the relevant controller for that menu item by passing in the $index to let the app know which one we need. However I need to also pass in the $index from the outer ng-repeat so the app knows which section we are in as well as which tutorial.
<ul ng-repeat="section in sections"> <li class="section_title {{section.active}}" > {{section.name}} </li> <ul> <li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu($index)" ng-repeat="tutorial in section.tutorials"> {{tutorial.name}} </li> </ul> </ul>
here's a Plunker http://plnkr.co/edit/bJUhI9oGEQIql9tahIJN?p=preview
Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.
The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.
Each ng-repeat creates a child scope with the passed data, and also adds an additional $index
variable in that scope.
So what you need to do is reach up to the parent scope, and use that $index
.
See http://plnkr.co/edit/FvVhirpoOF8TYnIVygE6?p=preview
<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu($parent.$index)" ng-repeat="tutorial in section.tutorials"> {{tutorial.name}} </li>
Way more elegant solution than $parent.$index
is using ng-init
:
<ul ng-repeat="section in sections" ng-init="sectionIndex = $index"> <li class="section_title {{section.active}}" > {{section.name}} </li> <ul> <li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(sectionIndex)" ng-repeat="tutorial in section.tutorials"> {{tutorial.name}} </li> </ul> </ul>
Plunker: http://plnkr.co/edit/knwGEnOsAWLhLieKVItS?p=info
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With