[英]access ng-repeat $index from a inner ng-repeat
知道ng-repeat創建了作用域后,如何從子ng-repeat
訪問父ng-repeat的$index
?
標記
<div ng-repeat="first in arr">
here there is the first level $index
<div ng-repeat="second in first.arr">
in here I need access to the first level $index
</div>
</div>
每當ng-repeat
迭代創建DOM時,它也會創建一個具有新作用域的DOM,新作用域通常是從當前運行的作用域繼承的。
當您想訪問內部ng-repeat
中外部ng-repeat
的ng-repeat
$ index時,可以使用$parent.$index
來指示父ng-repeat
<div ng-repeat="first in arr">
here there is the first level $index
<div ng-repeat="second in first.arr">
in here I need access to the first level {{$parent.$index}}
</div>
</div>
盡管解決此問題的更干凈的解決方案是,但在外部ng-repeat
上使用ng-init
並在scope變量中具有外部index
,通過該變量可以擺脫$parent
關鍵字。
<div ng-repeat="first in arr" ng-init="parentIndex=$index">
here there is the first level $index
<div ng-repeat="second in first.arr">
in here I need access to the first level {{parentIndex}}
</div>
</div>
<div ng-repeat="first in [1,2,3]">
here there is the first level {{$index}}
<div ng-repeat="second in ['a', 'b', 'c']">
in here I need access to the first level {{$parent.$index}} / {{$index}}
</div>
輸出:
here there is the first level 0
in here I need access to the first level 0 / 0
in here I need access to the first level 0 / 1
in here I need access to the first level 0 / 2
here there is the first level 1
in here I need access to the first level 1 / 0
in here I need access to the first level 1 / 1
in here I need access to the first level 1 / 2
here there is the first level 2
in here I need access to the first level 2 / 0
in here I need access to the first level 2 / 1
in here I need access to the first level 2 / 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.