如何在递归指令中访问父级

How to access parents in recursive directive?

本文关键字:访问 指令 递归      更新时间:2024-02-07

我正在使用https://github.com/dotJEM/angular-tree作为递归指令循环通过这种模型:

  $scope.model = [
      {
          label: 'parent1',
          children: [{
              label: 'child'
          }]
      }, 
      {
          label: 'parent2',
          children: [{
              label: 'child',
              children: [{
                  label: 'innerChild'
              }]
          }]
      }, 
      {
          label: 'parent3'
      }
  ];

在模板中,代码如下:

<div data-dx-start-with="model">
    <div data-ng-repeat="node in $dxPrior">
        <a class="list-group-item">
            <span class="icon" data-ng-click="toggle(node)"><i class=" icon ion-android-arrow-dropdown"></i>&nbsp;</span>
            <span>{{ node.label}} ({{node.children.length}})</span>
        </a>
        <ul data-ng-show="node.expanded" data-dx-connect="node.children"></ul>
    </div>
</div>


现在,我该如何访问每位家长?我希望能够构建树视图的面包屑。

例如:parent2>child>innerChild>。。。

如果我没有弄错的话,我可以通过使用$parent来获取每个节点的父节点。。。但我该如何让每位家长都参与进来呢?

我创建了一个plnkr来说明:http://plnkr.co/edit/DOc9k4jT9iysJLFvvg3u?p=preview

只需对其进行编程。生成一个函数,该函数将遍历父级,直到到达根,并在每个步骤中构造父级数组:

$scope.getParentsBreadcrumb = function (thisScope) {
  var parents = [];
  while (thisScope && thisScope.node) {
    parents.unshift (thisScope.node.label);
    thisScope = thisScope.$parent.$parent;
  }
  return parents.join(' > ')
}

然后在你想要打印面包屑的模板中调用它:

{{getParentsBreadcrumbs (this)}}