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

人盡茶涼 提交于 2020-01-11 14:26:09

问题


I am building a table and I have two ng-repeat for my table.

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>

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!


回答1:


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>

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.




回答2:


Of course, use $parent

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



回答3:


Using $parent can get you the parent scope's original array. From there, the array indexOf() function will get you the index of the element with respect to its array. In your code it looks like this

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


来源:https://stackoverflow.com/questions/27992723/how-to-get-the-index-of-an-parent-scope-array-ng-repeat-inside-child-ng-repeat

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