nested ng-repeat $parent.$index and $index

*爱你&永不变心* 提交于 2019-12-03 01:05:49

DEMO FIDDLE

That's because the directive ng-if creates a new scope for itself, when you refer to $parent, it access the immediate $parent's scope, i.e., the inner repeat expression's scope.

So if you want to achieve something you wanted like in the former, you may use this:

<div ng-repeat="i in list">
    <div ng-repeat="j in list2">
        <div ng-if="1">
            ({{$parent.$parent.$index}} {{$parent.$index}})
        </div>
    </div>
</div>

if you have more than one inner directives, you can use ng-init for storing $index in a variable for references in child scopes.

<div ng-repeat="i in list" ng-init="outerIndex=$index">
    <div ng-repeat="j in list2" ng-init="innerIndex=$index">
        <div ng-if="1">
            ({{outerIndex}} {{innerIndex}})
        </div>
    </div>
</div>

I strongly suggest you to go through this article on understanding scopes in angular

Instead of using ng-init you can use the (key, value) ng-repeat syntax to get the parent index.

DEMO

<div ng-repeat="(iKey, i) in list">
    <div ng-repeat="j in list2">
        <div ng-if="1">
            ({{iKey}} {{$index}})
        </div>
    </div>
</div>

check out the PLUNK

ng-if is creating a new child scope because of which there is a need to add $parent. i have created myname property which tells the scope name, using which you can check whats exactly happening..

<div ng-if="1">
    ({{$parent.$parent.$index}} {{$parent.$index}})
</div>

The ng-if introduce an another scope, so one $parent. isn't enough.

You could double it like this $parent.$parent.$index, or remember the index of the outer ng-repeat in a different variable via ng-init like this:

<div ng-repeat="i in list" ng-init="listIndex = $index">
  <div ng-repeat="j in list2">
    <div ng-if="1">
      ({{listIndex}} {{$index}})
    </div>
  </div>
</div>

Example plunker: http://plnkr.co/edit/dtaBAmkU32BCsLASLs0C?p=preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!