如何获取嵌套ng-repeat的父$索引

时间:2017-03-01 08:52:53

标签: javascript angularjs

任何人都知道如何获得嵌套$index的第一级ng-repeat

这是我的数据:

vm.rooms = [
      {
          name: 'Room1', students: ['Cal', 'Ryan', 'Luigi', 'Joel']
      },
      {
          name: 'Room2', students: ['Jaime', 'Sherwin', 'Gami', 'Beau']
      },
      {
          name: 'Room3', students: ['Roel', 'Edwin', 'Carl', 'Necho']
      }
  ]

我想得到这个输出:

Room1 - Idx: 0
    Cal - Idx: 0 on room idx: 0
    Ryan - Idx: 1 on room idx: 0
    Luigi - Idx: 2 on room idx: 0
    Joel - Idx: 3 on room idx: 0
Room2 - Idx: 1
    Jaime - Idx: 0 on room idx: 1
    Sherwin - Idx: 1 on room idx: 1
    Gami - Idx: 2 on room idx: 1
    Beau - Idx: 3 on room idx: 1
Room3 - Idx: 2
    Roel - Idx: 0 on room idx: 2
    Edwin - Idx: 1 on room idx: 2
    Carl - Idx: 2 on room idx: 2
    Necho - Idx: 3 on room idx: 2

但是我在DEMO中找到了这个,你可以检查那里的html结构。

2 个答案:

答案 0 :(得分:2)

您可以使用$ parent访问父级的范围。 所以使用

$parent.$index

答案 1 :(得分:2)

您可以使用

  

$母体。$索引

其他简单的解决方案是使用不同的变量

在ng-init中启动索引
<div ng-app="app"  ng-controller="ctrl">
  <div ng-repeat="i in [1,2,3,4]" ng-init="firstIndex=$index">
    <div ng-repeat="i in [1,2,3,4]" ng-init="secondIndex=$index">
      <div ng-repeat="i in [1,2,3,4]" ng-init="thirdIndex=$index">
      {{firstIndex}}:{{secondIndex}}:{{thirdIndex}}
      </div>
    </div>
  </div>
</div>

var app=angular.module("app",[]);
app.controller("ctrl",function($scope){

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app"  ng-controller="ctrl">
  <div ng-repeat="i in [1,2,3,4]" ng-init="firstIndex=$index">
    <div ng-repeat="i in [1,2,3,4]" ng-init="secondIndex=$index">
      <div ng-repeat="i in [1,2,3,4]" ng-init="thirdIndex=$index">
      {{firstIndex}}:{{secondIndex}}:{{thirdIndex}}
      </div>
    </div>
  </div>
</div>