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

Angular recursive ng-include while keeping track of recursion depth

本文关键字:递归 跟踪 深度 ng-include      更新时间:2023-09-26

我有一个非常类似于这个问题的答案的情况:

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

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

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

-blah
    -blahL11
    -blahL12
    -blahL13
            -blahL111

可以显示

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

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

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

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