Answers:
看看这个小提琴
原文:http: //jsfiddle.net/brendanowen/uXbn6/8/
更新:http : //jsfiddle.net/animaxf/uXbn6/4779/
这应该使您对如何显示tree like structure
使用角度有个好主意。这是在html中使用递归的一种!
如果您使用的是Bootstrap CSS ...
我已经基于Bootstrap“ nav”列表为AngularJS创建了一个简单的可重用树控件(指令)。我添加了额外的缩进,图标和动画。HTML属性用于配置。
它不使用递归。
我称它为angular-bootstrap-nav-tree(俗称,您不觉得吗?)
进行此类操作时,最好的解决方案是递归指令。但是,当您做出这样的指令时,您会发现AngularJS陷入了一个无限循环。
解决方案是让指令在compile事件期间删除该元素,然后手动进行编译并将其添加到link事件中。
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);
}
};
});
看到这个柱塞的演示。我最喜欢此解决方案,因为:
更新:添加了对自定义链接功能的支持。
angular-ui-tree似乎对我来说做得很好
以下是使用递归指令的示例: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);
});
};
}
};
});
这似乎更完整:https : //github.com/dump247/angular.tree
如此众多的出色解决方案,但我觉得它们都以一种或另一种方式使事情变得有些复杂。
我想创建一些东西来重新创建@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的“递归模板”遮篷中获得了更多收益,但是允许我们在需要树的位置定义模板。
(您可以使用基于脚本标签的模板来做到这一点,但是它仍然必须坐在实际的树节点的外面,并且仍然感觉有点......)
留在这里只是另一个选择...
您可以尝试将Angular-Ui-Tree 与Angular-Tree-DnD示例一起使用,但我已对其进行了编辑,与表格,网格,列表兼容。
基于@ganaraj的答案和@ dnc253的答案,我为具有选择,添加,删除和编辑功能的树结构制作了一个简单的“指令”。
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: '=',
}
}
});
是的,绝对有可能。这里的问题可能假设为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发挥其魔力。这个概念显然也适用于Angular1.x。
这是一个完整的示例:http : //www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0
您可以为此使用angular-recursion-injector:https : //github.com/knyga/angular-recursion-injector
使用条件可以进行无限深度的嵌套。仅在需要时才重新编译,并且仅编译正确的元素。代码中没有魔术。
<div class="node">
<span>{{name}}</span>
<node--recursion recursion-if="subNode" ng-model="subNode"></node--recursion>
</div>
使它比其他解决方案更快,更简单地工作的原因之一是后缀“-递归”。
当树结构很大时,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
不复杂。
<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"
}];
}]);