如何在子 ng-repeat 中获取父作用域数组/ng-repeat 的索引 [英] How to get the index of an parent scope array/ng-repeat inside child ng-repeat
问题描述
我正在构建一张桌子,我的桌子有两个 ng-repeat
.
I am building a table and I have two ng-repeat
for my table.
我的问题是 ng-repeat
的孩子是否有可能获得父 ng-repeat
的索引.例如:
My question is if it's possible the child of the ng-repeat
can get the parent ng-repeat
's index. For example:
<tbody>
<tr ng-repeat="company in companies">
<td ng-repeat="product in company">
company # = {{the company index}} and product {{$index}}
</td>
</tr>
</tbody>
我不知道如何在 td ng-repeat
下添加公司索引.有没有办法做到这一点?非常感谢!
I am not sure how to add the company index under the td ng-repeat
. Is there a way to do this? Thanks a lot!
推荐答案
这正是 ng-init
出现,为 ng-repeat 的特殊属性取别名,例如:ng-init="companyIdx=$index"
.因此,由公司 ng-repeat
创建的每个子作用域都将具有此 companyIdx
属性.
This is exactly where ng-init
comes into picture, to alias special properties of ng-repeat, ex: ng-init="companyIdx=$index"
. So each child scope created by company ng-repeat
will have this companyIdx
property.
<tbody>
<tr ng-repeat="company in companies" ng-init="companyIdx=$index">
<td ng-repeat="product in company">
company # = {{companyIdx}} and product {{$index}}
</td>
</tr>
</tbody>
使用 $parent
很好,但你有任何其他指令可以在它们之间创建一个子作用域,例如:- ng-if
,另一个 ng-repeat
等等.你将不得不疯狂地做 $parent.$parent....
.使用 ng-init
别名使其更清晰、更易读和更易于维护.
Using a $parent
is fine but it you have any other directive that creates a child scope in between them, eg:- ng-if
, another ng-repeat
etc.. you will have to go crazy doing $parent.$parent....
. Aliasing with ng-init
makes it clean and more readable and maintainable as well.
这篇关于如何在子 ng-repeat 中获取父作用域数组/ng-repeat 的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!