如何在子 ng-repeat 中获取父范围 array/ng-repeat 的索引

How to get the index of an parent scope array/ng-repeat inside child ng-repeat

我正在建造一个 table,我有两个 ng-repeat 用于我的 table。

我的问题是 ng-repeat 的子项是否有可能获得父项 ng-repeat 的索引。例如:

<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 下添加公司索引。有没有办法做到这一点?非常感谢!

当然用$parent

company # = {{$parent.$index}} and product {{$index}}

这正是 ng-init 出现的地方,为 ng-repeat 的特殊属性起别名,例如:ng-init="companyIdx=$index"。因此,公司 ng-repeat 创建的每个子范围都将具有此 companyIdx 属性.

<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 别名使它更干净,也更易读和可维护。

使用$parent可以获得父作用域的原始数组。从那里,数组 indexOf() 函数将为您获取元素相对于其数组的索引。在你的代码中它看起来像这样

<tr ng-repeat="company in companies">
    <td ng-repeat="product in company">
        company # = {{$parent.companies.indexOf(company)}} and product {{$index}}
    </td>
</tr>