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

后端 未结 3 398
广开言路
广开言路 2021-01-28 09:53

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

相关标签:
3条回答
  • 2021-01-28 10:09

    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>
    
    0 讨论(0)
  • 2021-01-28 10:11

    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.

    0 讨论(0)
  • 2021-01-28 10:13

    Of course, use $parent

    company # = {{$parent.$index}} and product {{$index}}
    
    0 讨论(0)
提交回复
热议问题