如何在递归指令中访问父母?

时间:2015-02-19 20:02:35

标签: javascript angularjs recursion tree

我使用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&gt;孩子&gt; innerChild&gt; ...

如果我没有弄错的话,我可以使用$ parent获取每个节点的父节点...但是我如何获得每个父节点?

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

1 个答案:

答案 0 :(得分:1)

只需编程即可。制作将通过父母走路的功能,直到到达根并在每一步构建父母阵列:

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

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

{{getParentsBreadcrumbs (this)}}