【问题标题】:How to get the index of an parent scope array/ng-repeat inside child ng-repeat如何在子 ng-repeat 中获取父范围数组/ng-repeat 的索引
【发布时间】:2015-03-15 13:48:15
【问题描述】:

我正在构建一张桌子,我的桌子上有两个 ng-repeat

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

【问题讨论】:

    标签: javascript html angularjs angularjs-scope angularjs-ng-repeat


    【解决方案1】:

    当然,使用$parent

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

    【讨论】:

      【解决方案2】:

      这正是 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 别名使其更干净、更易读和更易于维护。

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

        • 或者只是,$parent.$index
        猜你喜欢
        • 2013-01-26
        • 2014-09-29
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多