Shruthi Sathyanarayana Shruthi Sathyanarayana - 2 months ago 21
AngularJS Question

How to set index values to child rows in angular js

I have a requirement where I need to add index values for child rows. I have Group rows under which there will be child rows. I am

ng-repeat
and I am using
$index
for child's as shown:

HTML code:

<table ng-repeat="node in data">
<tr> <td> {{node.groupName}} </td> </tr>
<tbody ng-model="node.nodes">
<tr ng-repeat="node in node.nodes"> <td> {{$index}} </td> </tr>
</table>


But it is displaying as shown:

enter image description here

But I want it to display as shown:

enter image description here

I am new to Angular JS and not getting how to display it like this. How am I supposed to do that. Please help.

Answer

As far as I understood your question, you'd like to have something like that:

<table ng-repeat="group in data">
  <thead> 
    <th> {{group.name}} </th> 
  </thead>
  <tbody ng-repeat="item in group.items"> 
    <tr> 
      <td>{{getIndex($parent.$index - 1, $index)}} | {{item}} </td> 
    </tr> 
  </tbody>
</table>

    $scope.data = [
      {name: 'Group1', items: ['a','b']},           
      {name: 'Group2', items: [1,2,3]},
      {name: 'Group3', items: ['x', 'xx', 'xxx', 'xxxx']}
    ];

    $scope.getIndex = function(previousGroupIndex, currentItemIndex){
      if(previousGroupIndex >= 0){
        var previousGroupLength = getPreviousItemsLength(previousGroupIndex);
        return previousGroupLength + currentItemIndex;
      }
      return currentItemIndex;
    };

    function getPreviousItemsLength(currentIndex){
      var length = 0;
      for (var i = 0; i <= currentIndex; i++){
        length += $scope.data[i].items.length;
      }
      return length;
    }

You need to play with $parent.$index property and use some math :) in order to achieve that.

It would look like the following:

enter image description here

Check out this JSFiddle to see live example.