0

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.

Community
  • 1
  • 1
  • It's displaying like that because you are using index. Index will start over at 0 within each group. What does your data actually look like? Is there a reason you are using index instead of actual values? – Rani Radcliff Sep 14 '16 at 15:49
  • @ Rani Radcliff I don't want data to display there. I just want index values to display there as shown above. Is there any other method to do that?? – Shruthi Sathyanarayana Sep 14 '16 at 16:01

1 Answers1

1

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;

      // or even better to use Array.prototype.reduce() for that purpose
      // it would be shorter and beautiful
      // return $scope.data.reduce(function(previousValue, currentGroup, index){
      //    return index <= previousGroupIndex ? previousValue + currentGroup.items.length : previousValue;
      // }, 0);
    }

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.

Community
  • 1
  • 1
Artyom Pranovich
  • 6,814
  • 8
  • 41
  • 60