Angularjs - nested ng-repeat global index

114 Views Asked by At

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?

4

There are 4 best solutions below

2
Emirhan ÖZKAN On

You can use {{$index}} to show group index on your list.

0
Ahmet Amasyalı On

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>
0
Petr Averyanov On

Your options:

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

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>