簡體   English   中英

從內部ng-repeat訪問ng-repeat $ index

[英]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-repeatng-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM