使用angular指令构建嵌套树

时间:2015-02-28 08:25:46

标签: javascript angularjs

我在角度控制器中有像这样的数据

[
  {name: 'test', parent_id: 0, children_id: 2, id: 1}, 
  {name: 'test', parent_id: 1, children_id: 3, id: 2}, 
  {name: 'test', parent_id: 2, children_id: 0, id: 3}, 
  ...
];

我可以通过parent_idchildren_id构建嵌套树使用角度指令吗?

谢谢

2 个答案:

答案 0 :(得分:0)

您只能使用parent_id构建树。你甚至不需要children_id

答案 1 :(得分:0)

您可以在ng-repeat

中使用角度filter



angular.module('app', ['angular.filter'])
  .controller('MainController', function($scope) {
    $scope.parents = [{
        name: 'test',
        parent_id: 0,
        children_id: 2,
        id: 1
      }, {
        name: 'test',
        parent_id: 1,
        children_id: 3,
        id: 2
      }, {
        name: 'test',
        parent_id: 2,
        children_id: 0,
        id: 3
      }, {
        name: 'test 2',
        parent_id: 2,
        children_id: 0,
        id: 3
      }


    ];
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
<div ng-app="app" ng-controller="MainController">

  <ul ng-repeat="(parent, children) in parents | groupBy: 'parent_id'">
    parent: {{ parent }}
    <li ng-repeat="child in children">
      child: {{ child.name }}
    </li>
  </ul>
</div>
&#13;
&#13;
&#13;