我希望在Web应用程序中以树形结构显示数据.我希望使用Angular来完成这项任务.
看起来ng-repeat将允许我遍历节点列表,但是当给定节点的深度增加时,我怎么能进行嵌套呢?
我尝试了以下代码,但HTML的自动转义阻止了它的工作.另外,结束ul标签位置错误.
我很确定我完全以错误的方式解决这个问题.
有任何想法吗?
gan*_*raj 230
看看这个小提琴
原文:http: //jsfiddle.net/brendanowen/uXbn6/8/
更新:http://jsfiddle.net/animaxf/uXbn6/4779/
这应该可以让您了解如何显示tree like structure
使用角度.它是一种在html中使用递归!
Nic*_*ins 77
如果您使用的是Bootstrap CSS ...
我已经基于Bootstrap"nav"列表为AngularJS创建了一个简单的可重用树控件(指令).我添加了额外的缩进,图标和动画.HTML属性用于配置.
它不使用递归.
我叫它angular-bootstrap-nav-tree(上口名字,你不觉得吗?)
Mar*_*ijk 35
在制作这样的东西时,最好的解决方案是递归指令.但是,当你制作这样的指令时,你会发现AngularJS进入无限循环.
解决方案是让指令在编译事件期间删除元素,并手动编译并在链接事件中添加它们.
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);
}
}
};
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
使用此服务,您可以轻松地创建树指令(或其他递归指令).以下是树指令的示例:
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);
}
};
});
Run Code Online (Sandbox Code Playgroud)
有关演示,请参阅此Plunker.我最喜欢这个解决方案,因为:
更新:添加了对自定义链接功能的支持.
sav*_*nda 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);
});
};
}
};
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
186242 次 |
最近记录: |