角度递归 ng-include 同时跟踪递归深度

Ram*_*ing 5 javascript recursion angularjs

我遇到的情况与这里问题的答案非常相似:

具有嵌套层次结构的 AngularJS ng-include

我有一些格式的数据

 $scope.data = {
text: "blah",
comments: 
[
  {
    text: ["blahL11", "blahL12", "blahL13"],
    comments: [
      { 
        text: ["blahL111", "blahL112", "blahL113"] 
      },
      { 
        text: ["blahR111", "blahR112", "blahR113"] 
      }
    ]
  },
  {
    text: ["blahR11", "blahR12", "blahR13"] 
  }
]
Run Code Online (Sandbox Code Playgroud)

};

我用递归 ng-include 显示它,如下所示:

  <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>
Run Code Online (Sandbox Code Playgroud)

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

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

-blah
    -blahL11
    -blahL12
    -blahL13
            -blahL111
Run Code Online (Sandbox Code Playgroud)

它可以显示

-1. blah    
    -2. blahL11
    -2. blahL12
    -2. blahL13
        -3. blahL111
Run Code Online (Sandbox Code Playgroud)

无需我修改数据结构(因为深度仅用于显示?)。我可以在 ng-include 中插入一个变量吗?我可以使用某种递归 $index 吗?

Jam*_*ley 4

您可以使用 来执行此操作ng-init。这将在创建新作用域时为其分配一个值,您可以通过引用旧作用域中的值并递增它来完成此操作。

plnkr 演示

<li ng-repeat="item in item.comments" ng-include="'tree'" ng-init="depth = depth + 1"></li>
Run Code Online (Sandbox Code Playgroud)