Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain index in nested ng-repeats

Tags:

angularjs

I have an ng-repeat within a ng-repeat. I am tyring to obtain the index at both levels but am not able to :

<tbody>
    <tr ng-repeat="element in body">
      <td ng-repeat="h in header" style="width:{{h.width}}px">
        <div col="{{$parent.$parent.$index}}" row="{{$parent.$index}}">{{element[h.column]}}</div>
      <td>
    </tr>
  </tbody>  

here is a plnkr too. http://plnkr.co/edit/dGoN43HzQefVpCsp2R3j

The ISSUE is that value of "col" never gets populated. It does not capture the index. Can anyone assist

like image 944
runtimeZero Avatar asked Mar 25 '14 17:03

runtimeZero


People also ask

How do I get an index value in ng-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.

How do I use track in NG-repeat?

To avoid this problem, you can use "track by" with ng-repeat. In track by you have to use angular expression that will be used to uniquely identify the each items in collection or model. "track by" tells the angular js that how angular js will track the association between DOM and the model (i.e. collection).

What can I use instead of NG-repeat?

The *ngFor directive in Angular is like the ng-repeat directive in AngularJS. It repeats the associated DOM element for each item in the specified collection.

What is $Index track?

When using Ng-repeat with the 'track by $index' feature, it allows you, as you may have guessed, to keep track of the indexes of the array that are being iterated over. This is extremely useful when you have an array of objects and you need to access properties within those objects.


1 Answers

You do not have to use $parent, just use $index to get index of inner loop and use indexOf() function of array to get index of outer loop...

HTML

<tr ng-repeat="element in body">
  <td ng-repeat="h in header" style="width:{{h.width}}px">
    <div col="{{body.indexOf(element)}}" row="{{$index}}">{{element[h.column]}}</div>
  <td>
</tr>

UPDATE

Actually using ng-init would much better to get index of outer loop... here you can easily set rowIndex to current index at every turn and use it in inner loop...

  <tbody>
    <tr ng-repeat="element in body" ng-init="rowIndex = $index">
      <td ng-repeat="h in header" style="width:{{h.width}}px">
        <div col="{{$index}}" row="{{rowIndex}}">{{element[h.column]}}</div>
      <td>
    </tr>
  </tbody> 

here is updated PLUNKER

like image 52
Poyraz Yilmaz Avatar answered Sep 27 '22 16:09

Poyraz Yilmaz