简体   繁体   中英

Angularjs - nested ng-repeat global index

I have next template:

<div data-ng-repeat="supplier in order.Suppliers" data-ng-init="supplierIndex = $index">
    <div data-ng-repeat="group in supplier.Groups">
         {{something}}
    </div>
</div>

And model:

$scope.order = {
    Suppliers: [
        {
            Groups: [{ id: 'sss'}, {id: 'ddd'}]
        },
        {
            Groups: [{ id: 'qqqq'}, {id: 'www'}, {id: 'xxx'}]
        },
        {
            Groups: [{ id: 'ooo'}]
        }
    ]
}

I need to display global group index, so output should be like this:

0 1 2 3 4 5

I know that I can use function that calculate index by passed group id at each place we need to display global group index, but how to accomplish this goal most gracefully?

您可以使用{{$index}}在列表中显示组索引。

You can merge groups like this in your controller.

 $scope.mergedGroups = [];
  for(var i=0;  i < $scope.order.Suppliers.length;  i++){
    for(var k=0;  k < $scope.order.Suppliers[i].Groups.length;  k++){
       $scope.mergedGroups.push($scope.order.Suppliers[i].Groups[k]);
    }
  }

then you can use a single ng-repeat and its done.

<div data-ng-repeat="group in mergedGroups" >
    {{group}} {{$index}}
</div>

Your options:

  1. $parent.$index
  2. put supplier index inside supplier object
  3. create component <supplier-info supplier="supplier" index="$index">

If done only in html:

<div data-ng-init="$parent.index = 0" data-ng-repeat="supplier in order.Suppliers">
  <div data-ng-repeat="group in supplier.Groups">
    <span data-ng-init="index=$parent.$parent.index;$parent.$parent.index = $parent.$parent.index + 1;">
      {{index}}
    </span>
  </div>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM