Access index of the parent ng-repeat from child ng-repeat

后端 未结 6 676
不思量自难忘°
不思量自难忘° 2020-11-28 19:43

I want to use the index of the parent list (foos) as an argument to a function call in the child list (foos.bars).

I found a post where someone recommends using $par

相关标签:
6条回答
  • 2020-11-28 19:56

    You can simply use use $parent.$index .where parent will represent object of parent repeating object .

    0 讨论(0)
  • 2020-11-28 20:01

    Take a look at my answer to a similar question.
    By aliasing $index we do not have to write crazy stuff like $parent.$parent.$index.


    Way more elegant solution whan $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

    0 讨论(0)
  • 2020-11-28 20:03

    You can also get control of grand parent index by the following code

    $parent.$parent.$index
    
    0 讨论(0)
  • 2020-11-28 20:04

    My example code was correct and the issue was something else in my actual code. Still, I know it was difficult to find examples of this so I'm answering it in case someone else is looking.

    <div ng-repeat="f in foos">
      <div>
        <div ng-repeat="b in foos.bars">
          <a ng-click="addSomething($parent.$index)">Add Something</a>
        </div>
      </div>
    </div>
    
    0 讨论(0)
  • 2020-11-28 20:10

    $parent doesn't work if there are multiple parents. instead of that we can define a parent index variable in init and use it

    <div data-ng-init="parentIndex = $index" ng-repeat="f in foos">
      <div>
        <div data-ng-init="childIndex = $index" ng-repeat="b in foos.bars">
          <a ng-click="addSomething(parentIndex)">Add Something</a>
        </div>
      </div>
    </div>
    
    0 讨论(0)
  • 2020-11-28 20:16

    According to ng-repeat docs http://docs.angularjs.org/api/ng.directive:ngRepeat, you can store the key or array index in the variable of your choice. (indexVar, valueVar) in values

    so you can write

    <div ng-repeat="(fIndex, f) in foos">
      <div>
        <div ng-repeat="b in foos.bars">
          <a ng-click="addSomething(fIndex)">Add Something</a>
        </div>
      </div>
    </div>
    

    One level up is still quite clean with $parent.$index but several parents up, things can get messy.

    Note: $index will continue to be defined at each scope, it is not replaced by fIndex.

    0 讨论(0)
提交回复
热议问题