2015-09-03 77 views
4

我有一个情况,这是非常类似于此问题的答案在这里:角递归NG-包括同时跟踪递归深度的

AngularJS ng-include with nested hierarchy

我有一些数据格式

$scope.data = { 
text: "blah", 
comments: 
[ 
    { 
    text: ["blahL11", "blahL12", "blahL13"], 
    comments: [ 
     { 
     text: ["blahL111", "blahL112", "blahL113"] 
     }, 
     { 
     text: ["blahR111", "blahR112", "blahR113"] 
     } 
    ] 
    }, 
    { 
    text: ["blahR11", "blahR12", "blahR13"] 
    } 
] 

};

而且我有一个递归显示它NG-包括这样的:

<ul> 
    <li>{{data.text}}</li> 
    <li ng-repeat="item in data.comments" ng-include="'tree'"></li> 
</ul> 

<script type="text/ng-template" id="tree"> 
    <ul> 
    <li ng-repeat="text in item.text">{{text}}</li> 
    <li ng-repeat="item in item.comments" ng-include="'tree'"></li> 
    </ul> 
</script> 

http://plnkr.co/edit/8swLos2V6QRz6ct6GDGb?p=info

不过,我想以某种方式跟踪递归的深度为好。这样的而不是简单地显示:

-blah 
    -blahL11 
    -blahL12 
    -blahL13 
      -blahL111 

它可以显示

-1. blah  
    -2. blahL11 
    -2. blahL12 
    -2. blahL13 
     -3. blahL111 

没有我修改的数据结构(如深度是唯一真正用于显示?)。我可以在ng-include中插入一个变量,是否有某种我可以使用的递归$索引?

+0

看看https://github.com/dotJEM/angular-tree,它有这个内置否则作品配发像递归NG-包括。 – Jens

回答

3

您可以使用ng-init来做到这一点。这将在创建新范围时为其分配一个值,您可以通过引用旧范围中的值并将其增加来为其创建值。

plnkr demo

<li ng-repeat="item in item.comments" ng-include="'tree'" ng-init="depth = depth + 1"></li> 
+0

太棒了!我试图使用onload,没有想到ng-init。谢谢! – RamblerToning