2015-09-03 108 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