2016-09-14 36 views
0

我有一个需求,即需要为子行添加索引值。我有组行,其下会有子行。我ng-repeat,我使用$index为孩子的,如下所示:如何将索引值设置为角js中的子行

HTML代码:

<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> 

但它显示如:

enter image description here

但我想它显示为如图所示:

enter image description here

我是新来的Angular JS,并没有得到如何显示它像这样。我该怎么做。请帮忙。

+0

因为您正在使用索引,所以它的显示方式如此。索引将从每组中的0开始。你的数据实际上是什么样的?有没有理由使用索引而不是实际值? –

+0

@ Rani Radcliff我不希望数据在那里显示。我只是想索引值显示在那里,如上所示。有没有其他方法可以做到这一点? –

回答

1

据我理解你的问题,你想有这样的事情:

<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); 
    } 

您需要$parent.$index性能发挥和利用一些数学:),以实现这一目标。

它看起来像下面这样:

enter image description here

退房this JSFiddle看到活生生的例子。

+0

它给出像{0,3},{0,3,5}这样的值。但我想要{0,1},(2,3,4) –

+0

@ShruthiSathyanarayana,请看看我更新的答案,也许它需要修改您的初始数据集以适应。 –

+0

@ShruthiSathyanarayana,它有帮助吗? –