【问题标题】:Angular recursive ng-include while keeping track of recursion depth角递归 ng-include,同时跟踪递归深度
【发布时间】:2017-12-05 00:22:44
【问题描述】:

我的情况与此处问题的答案非常相似:

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 中插入一个变量吗,我可以使用某种递归 $index 吗?

【问题讨论】:

标签: javascript angularjs recursion


【解决方案1】:

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

plnkr demo

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

【讨论】:

  • 太棒了!我试图使用onload,没有想到ng-init。谢谢!
猜你喜欢
  • 2010-10-25
  • 1970-01-01
  • 2019-01-12
  • 2012-03-12
  • 2016-04-13
  • 2013-08-02
  • 2010-11-16
  • 2022-01-23
  • 2017-02-20
相关资源
最近更新 更多