是否可以使用Angular创建树视图?

时间:2012-08-07 21:38:36

标签: angularjs

我希望在网络应用中以树形结构显示数据。我希望使用Angular来完成这项任务。

看起来ng-repeat将允许我遍历节点列表,但是当给定节点的深度增加时,如何进行嵌套?

我尝试了following code,但HTML的自动转义阻止了它的运行。另外,最终的ul标签位置错误。

我很确定我完全以错误的方式解决这个问题。

有什么想法吗?

14 个答案:

答案 0 :(得分:228)

看看这个小提琴

原文:http://jsfiddle.net/brendanowen/uXbn6/8/

更新:http://jsfiddle.net/animaxf/uXbn6/4779/

这可以让您更好地了解如何使用角度显示tree like structure。它有点在html中使用递归!

答案 1 :(得分:77)

如果您使用的是Bootstrap CSS ...

我已经基于Bootstrap“nav”列表为AngularJS创建了一个简单的可重用树控件(指令)。我添加了额外的缩进,图标和动画。 HTML属性用于配置。

它不使用递归。

我称之为 angular-bootstrap-nav-tree (引人注目的名字,你不觉得吗?)

有一个示例here,来源为here

答案 2 :(得分:35)

制作这样的东西时,最好的解决方案是递归指令。但是,当你做出这样的指令时,你会发现AngularJS进入无限循环。

解决方法是让指令在编译事件期间删​​除元素,并手动编译并在链接事件中添加它们。

我在this thread中发现了这一点,并抽象了这个功能into a service

module.factory('RecursionHelper', ['$compile', function($compile){
    return {
        /**
         * Manually compiles the element, fixing the recursion loop.
         * @param element
         * @param [link] A post-link function, or an object with function(s) registered via pre and post properties.
         * @returns An object containing the linking functions.
         */
        compile: function(element, link){
            // Normalize the link parameter
            if(angular.isFunction(link)){
                link = { post: link };
            }

            // Break the recursion loop by removing the contents
            var contents = element.contents().remove();
            var compiledContents;
            return {
                pre: (link && link.pre) ? link.pre : null,
                /**
                 * Compiles and re-adds the contents
                 */
                post: function(scope, element){
                    // Compile the contents
                    if(!compiledContents){
                        compiledContents = $compile(contents);
                    }
                    // Re-add the compiled contents to the element
                    compiledContents(scope, function(clone){
                        element.append(clone);
                    });

                    // Call the post-linking function, if any
                    if(link && link.post){
                        link.post.apply(null, arguments);
                    }
                }
            };
        }
    };
}]);

使用此服务,您可以轻松制作树指令(或其他递归指令)。以下是树指令的示例:

module.directive("tree", function(RecursionHelper) {
    return {
        restrict: "E",
        scope: {family: '='},
        template: 
            '<p>{{ family.name }}</p>'+
            '<ul>' + 
                '<li ng-repeat="child in family.children">' + 
                    '<tree family="child"></tree>' +
                '</li>' +
            '</ul>',
        compile: function(element) {
            return RecursionHelper.compile(element);
        }
    };
});

有关演示,请参阅此Plunker。 我最喜欢这个解决方案,因为:

  1. 您不需要特殊的指令,这会使您的HTML不那么干净。
  2. 递归逻辑被抽象到RecursionHelper服务中,因此您可以保持指令清洁。
  3. 更新:添加了对自定义链接功能的支持。

答案 3 :(得分:16)

angular-ui-tree似乎为我做得很好

答案 4 :(得分:14)

以下是使用递归指令的示例:http://jsfiddle.net/n8dPm/ 取自https://groups.google.com/forum/#!topic/angular/vswXTes_FtM

module.directive("tree", function($compile) {
return {
    restrict: "E",
    scope: {family: '='},
    template: 
        '<p>{{ family.name }}</p>'+
        '<ul>' + 
            '<li ng-repeat="child in family.children">' + 
                '<tree family="child"></tree>' +
            '</li>' +
        '</ul>',
    compile: function(tElement, tAttr) {
        var contents = tElement.contents().remove();
        var compiledContents;
        return function(scope, iElement, iAttr) {
            if(!compiledContents) {
                compiledContents = $compile(contents);
            }
            compiledContents(scope, function(clone, scope) {
                     iElement.append(clone); 
            });
        };
    }
};
});

答案 5 :(得分:12)

这个似乎更完整:https://github.com/dump247/angular.tree

答案 6 :(得分:5)

基于original source的另一个示例,已经有一个示例树结构(更容易看到它如何工作IMO)和一个搜索树的过滤器:

JSFiddle

答案 7 :(得分:4)

这么多很棒的解决方案,但我觉得他们都有某种方式过于复杂化了。

我想创建一些东西,重新创建@Mark Lagendijk的awnser的简单性,但没有在指令中定义模板,而是让“用户”在HTML中创建模板......

根据https://github.com/stackfull/angular-tree-repeat等提出的想法......我最终创建了项目:https://github.com/dotJEM/angular-tree

允许您构建树,如:

<ul dx-start-with="rootNode">
  <li ng-repeat="node in $dxPrior.nodes">
    {{ node.name }}
    <ul dx-connect="node"/>
  </li>
</ul>

对我来说比为不同结构化的树创建多个指令要干净得多....本质上调用上面的树有点假,它从@ ganaraj的“递归模板”中获取更多信息,但是允许我们定义我们需要树的模板。

(你可以用基于脚本标签的模板做到这一点,但它仍然必须坐在实际的树节点之外,它仍然只是感觉有点yuk ......)

留在这里只是另一种选择......

答案 8 :(得分:3)

您可以尝试使用Angular-Ui-Tree的Angular-Tree-DnD示例,但我编辑了,与表格,网格,列表兼容。

  • Able Drag&amp;降
  • 列表的扩展函数指令(next,prev,getChildren,...)
  • 过滤数据。
  • OrderBy(ver)

答案 9 :(得分:2)

基于@ganaraj的answer和@ dnc253的answer,我为树结构做了一个简单的“指令”,它具有选择,添加,删除和编辑功能。 / p>

Jsfiddle:http://jsfiddle.net/yoshiokatsuneo/9dzsms7y/

HTML:

<script type="text/ng-template" id="tree_item_renderer.html">
    <div class="node"  ng-class="{selected: data.selected}" ng-click="select(data)">
        <span ng-click="data.hide=!data.hide" style="display:inline-block; width:10px;">
            <span ng-show="data.hide && data.nodes.length > 0" class="fa fa-caret-right">+</span>
            <span ng-show="!data.hide && data.nodes.length > 0" class="fa fa-caret-down">-</span>
        </span>
        <span ng-show="!data.editting" ng-dblclick="edit($event)" >{{data.name}}</span>
        <span ng-show="data.editting"><input ng-model="data.name" ng-blur="unedit()" ng-focus="f()"></input></span>
        <button ng-click="add(data)">Add node</button>
        <button ng-click="delete(data)" ng-show="data.parent">Delete node</button>
    </div>
    <ul ng-show="!data.hide" style="list-style-type: none; padding-left: 15px">
        <li ng-repeat="data in data.nodes">
            <recursive><sub-tree data="data"></sub-tree></recursive>
        </li>
    </ul>
</script>
<ul ng-app="Application" style="list-style-type: none; padding-left: 0">
    <tree data='{name: "Node", nodes: [],show:true}'></tree>
</ul>

JavaScript的:

angular.module("myApp",[]);

/* https://stackoverflow.com/a/14657310/1309218 */
angular.module("myApp").
directive("recursive", function($compile) {
    return {
        restrict: "EACM",
        require: '^tree',
        priority: 100000,

        compile: function(tElement, tAttr) {
            var contents = tElement.contents().remove();
            var compiledContents;
            return function(scope, iElement, iAttr) {
                if(!compiledContents) {
                    compiledContents = $compile(contents);
                }
                compiledContents(scope, 
                                     function(clone) {
                         iElement.append(clone);
                                         });
            };
        }
    };
});

angular.module("myApp").
directive("subTree", function($timeout) {
    return {
        restrict: 'EA',
        require: '^tree',
        templateUrl: 'tree_item_renderer.html',
        scope: {
            data: '=',
        },
        link: function(scope, element, attrs, treeCtrl) {
            scope.select = function(){
                treeCtrl.select(scope.data);
            };
            scope.delete = function() {
                scope.data.parent.nodes.splice(scope.data.parent.nodes.indexOf(scope.data), 1);
            };
            scope.add = function() {
                var post = scope.data.nodes.length + 1;
                var newName = scope.data.name + '-' + post;
                scope.data.nodes.push({name: newName,nodes: [],show:true, parent: scope.data});
            };
            scope.edit = function(event){
                scope.data.editting = true;
                $timeout(function(){event.target.parentNode.querySelector('input').focus();});
            };
            scope.unedit = function(){
                scope.data.editting = false;
            };

        }
    };
});


angular.module("myApp").
directive("tree", function(){
    return {
        restrict: 'EA',
        template: '<sub-tree data="data" root="data"></sub-tree>',
        controller: function($scope){
            this.select = function(data){
                if($scope.selected){
                    $scope.selected.selected = false;
                }
                data.selected = true;
                $scope.selected = data;
            };
        },
        scope: {
            data: '=',
        }
    }
});

答案 10 :(得分:0)

是的,这绝对有可能。这里的问题可能假定为Angular 1.x,但为了将来参考,我将包括一个Angular 2示例:

从概念上讲,您所要做的就是创建一个递归模板:

<ul>
    <li *for="#dir of directories">

        <span><input type="checkbox" [checked]="dir.checked" (click)="dir.check()"    /></span> 
        <span (click)="dir.toggle()">{{ dir.name }}</span>

        <div *if="dir.expanded">
            <ul *for="#file of dir.files">
                {{file}}
            </ul>
            <tree-view [directories]="dir.directories"></tree-view>
        </div>
    </li>
</ul>

然后将树对象绑定到模板,让Angular发挥其魔力。这个概念显然也适用于Angular 1.x。

以下是一个完整的示例:http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0

答案 11 :(得分:0)

您可以使用角度递归注入器:https://github.com/knyga/angular-recursion-injector

允许您使用条件进行无限深度嵌套。仅在需要时重新编译并仅编译正确的元素。代码没有魔力。

<div class="node">
  <span>{{name}}</span>

  <node--recursion recursion-if="subNode" ng-model="subNode"></node--recursion>
</div>

允许它比其他解决方案更快更简单的工作之一是“--recursion”后缀。

答案 12 :(得分:0)

当树结构很大时,Angular(最高1.4.x)在渲染递归模板时变得非常慢。在尝试了许多这些建议之后,我最终创建了一个简单的HTML字符串并使用ng-bind-html来显示它。当然,这不是使用Angular功能的方法

此处显示了一个简单的递归函数(使用最少的HTML):

function menu_tree(menu, prefix) {
    var html = '<div>' + prefix + menu.menu_name + ' - ' + menu.menu_desc + '</div>\n';
    if (!menu.items) return html;
    prefix += menu.menu_name + '/';
    for (var i=0; i<menu.items.length; ++i) {
        var item = menu.items[i];
        html += menu_tree(item, prefix);
    }
    return html;
}
// Generate the tree view and tell Angular to trust this HTML
$scope.html_menu = $sce.trustAsHtml(menu_tree(menu, ''));

在模板中,它只需要这一行:

<div ng-bind-html="html_menu"></div>

这绕过了Angular的所有数据绑定,只需在递归模板方法的一小部分时间内显示HTML。

使用这样的菜单结构(Linux文件系统的部分文件树):

menu = {menu_name: '', menu_desc: 'root', items: [
            {menu_name: 'bin', menu_desc: 'Essential command binaries', items: [
                {menu_name: 'arch', menu_desc: 'print machine architecture'},
                {menu_name: 'bash', menu_desc: 'GNU Bourne-Again SHell'},
                {menu_name: 'cat', menu_desc: 'concatenate and print files'},
                {menu_name: 'date', menu_desc: 'display or set date and time'},
                {menu_name: '...', menu_desc: 'other files'}
            ]},
            {menu_name: 'boot', menu_desc: 'Static files of the boot loader'},
            {menu_name: 'dev', menu_desc: 'Device files'},
            {menu_name: 'etc', menu_desc: 'Host-specific system configuration'},
            {menu_name: 'lib', menu_desc: 'Essential shared libraries and kernel modules'},
            {menu_name: 'media', menu_desc: 'Mount point for removable media'},
            {menu_name: 'mnt', menu_desc: 'Mount point for mounting a filesystem temporarily'},
            {menu_name: 'opt', menu_desc: 'Add-on application software packages'},
            {menu_name: 'sbin', menu_desc: 'Essential system binaries'},
            {menu_name: 'srv', menu_desc: 'Data for services provided by this system'},
            {menu_name: 'tmp', menu_desc: 'Temporary files'},
            {menu_name: 'usr', menu_desc: 'Secondary hierarchy', items: [
                {menu_name: 'bin', menu_desc: 'user utilities and applications'},
                {menu_name: 'include', menu_desc: ''},
                {menu_name: 'local', menu_desc: '', items: [
                    {menu_name: 'bin', menu_desc: 'local user binaries'},
                    {menu_name: 'games', menu_desc: 'local user games'}
                ]},
                {menu_name: 'sbin', menu_desc: ''},
                {menu_name: 'share', menu_desc: ''},
                {menu_name: '...', menu_desc: 'other files'}
            ]},
            {menu_name: 'var', menu_desc: 'Variable data'}
        ]
       }

输出变为:

- root
/bin - Essential command binaries
/bin/arch - print machine architecture
/bin/bash - GNU Bourne-Again SHell
/bin/cat - concatenate and print files
/bin/date - display or set date and time
/bin/... - other files
/boot - Static files of the boot loader
/dev - Device files
/etc - Host-specific system configuration
/lib - Essential shared libraries and kernel modules
/media - Mount point for removable media
/mnt - Mount point for mounting a filesystem temporarily
/opt - Add-on application software packages
/sbin - Essential system binaries
/srv - Data for services provided by this system
/tmp - Temporary files
/usr - Secondary hierarchy
/usr/bin - user utilities and applications
/usr/include -
/usr/local -
/usr/local/bin - local user binaries
/usr/local/games - local user games
/usr/sbin -
/usr/share -
/usr/... - other files
/var - Variable data

答案 13 :(得分:-2)

并不复杂。

<div ng-app="Application" ng-controller="TreeController">
    <table>
        <thead>
            <tr>
                <th>col 1</th>
                <th>col 2</th>
                <th>col 3</th>
            </tr>
        </thead>
        <tbody ng-repeat="item in tree">
            <tr>
                <td>{{item.id}}</td>
                <td>{{item.fname}}</td>
                <td>{{item.lname}}</td>
            </tr>
            <tr ng-repeat="children in item.child">
                <td style="padding-left:15px;">{{children.id}}</td>
                <td>{{children.fname}}</td>
            </tr>
        </tbody>
     </table>
</div>

控制器代码:

angular.module("myApp", []).
controller("TreeController", ['$scope', function ($scope) {
    $scope.tree = [{
        id: 1,
        fname: "tree",
        child: [{
            id: 1,
            fname: "example"
        }],
        lname: "grid"
    }];


}]);
相关问题