Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing 2 $index values within nested ng-repeat

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

like image 771
Tules Avatar asked Mar 06 '13 19:03

Tules


People also ask

How do I get the index of an element in NG-repeat?

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.

How does ng-repeat work?

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.


2 Answers

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> 
like image 80
Alex Osborn Avatar answered Oct 27 '22 22:10

Alex Osborn


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

like image 26
vucalur Avatar answered Oct 27 '22 22:10

vucalur