AngularJS:具有任意深度的嵌套列表

AngularJS: Nested Lists with Arbitrary depth

本文关键字:嵌套 列表 深度 任意 AngularJS      更新时间:2024-01-04

给定此处的解决方案,http://jsfiddle.net/brendanowen/uXbn6/8/关于这里发布的问题,有可能用Angular制作树状视图吗?

而Fiddle的例子可以让你生成一个嵌套列表,自由地显示它的深度。我更关心的是如何显示它,就像WordPress中的类别小部件一样。

angular.module("myApp", []).
controller("TreeController", ['$scope', function($scope) {
    $scope.delete = function(data) {
        data.nodes = [];
    };
    $scope.add = function(data) {
        var post = data.nodes.length + 1;
        var newName = data.name + '-' + post;
        data.nodes.push({name: newName,nodes: []});
    };
    $scope.tree = [{name: "Node", nodes: []}];
}]);
ul {
    list-style: circle;
}
li {
    margin-left: 20px;
}
<script src="https://code.angularjs.org/angular-1.0.0rc8.js"></script>
<script type="text/ng-template"  id="tree_item_renderer.html">
    {{data.name}}
    <button ng-click="add(data)">Add node</button>
    <button ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button>
    <ul>
        <li ng-repeat="data in data.nodes" ng-include="'tree_item_renderer.html'"></li>
    </ul>
</script>
<ul ng-app="Application" ng-controller="TreeController">
    <li ng-repeat="data in tree" ng-include="'tree_item_renderer.html'"></li>
</ul>

在angular中显示和修改基本相同,因为它有双向数据绑定。所以在你发布的例子中,只需用你的树数据填充$scope.tree变量,视图就会渲染它

此外,您可能对angular ui树模块感兴趣,该模块为树提供了一些开箱即用的功能:https://github.com/angular-ui-tree/angular-ui-tree