Adi.S
Adi.S

Reputation: 43

AngularJS nested ng-repeat indexing

I have this array of objects (left side) and I want to index it like this (right side) using ng-repeat.

 i   j        |  x
[             |     
 0            |  0   x = i
 1            |  1
 2            |  2
 3 [          |  
     0        |  3   x = i + j
     1        |  4
     2        |  5
   ]          |  
 4            |  6   x = ?
 5 [          |  
     0        |  7   x = ?
     1        |  8
     2        |  9
   ]          |
]             |

It kinda works with using $parent.$index+$index in the nested array, but this works only in the first nested array as the next ones will have their $index start at 0 again so 5+0 = 5, not 7. Also, the indexing of the main array will not count for the nested array elements after.

What I actually need is a counter which I can display in a {{}} block.

<div ng-repeat-start="item in array track by $index">
   {{$index}}
</div>
<div ng-if="isArray(item)" ng-repeat="subItem in item track by $index">
   {{$parent.$index+$index}}
</div>
<hr ng-repeat-stop>

I was thinking that maybe storing "x" as a member in each item from the array could work, but then every time I would remove one item from the array I will have to process the array again to fix the "x".

edit: My array is actually the content of a shopping cart. Each item in the array is a Product, but some of these items can be a Package that includes more products along a discount.

Upvotes: 1

Views: 307

Answers (1)

Adi.S
Adi.S

Reputation: 43

After a bit of rethinking the entire problem I came to the conclusion that indexing this nested array using ng-repeats complicates the page too much and by flattening the array I would solve more problems than I would create.

TL:DR I've flattened the array and by doing this I've simplified many more pages and only had to add a few new functions to deal with the packages' discounts.

Upvotes: 1

Related Questions