Jon*_*Jon 10 angularjs angularjs-directive angularjs-ng-repeat
我正在尝试使用AngularJS创建树视图.
这是我的代码:
module.directive('treeview', function () {
return {
restrict: 'E',
templateUrl: "/templates/ui/controls/treeview.htm",
replace: true,
transclude: true,
scope: {},
link: function (scope, element, attrs) {
console.log("treeview directive loaded");
},
controller: function ($scope, $rootScope) {
$rootScope.depth = 0;
$scope.items = [
{ text: "face" },
{ text: "palm" },
{
text: "cake",
childitems: [
{ text: "1 face" },
{ text: "1 palm" },
{ text: "1 cake" }
]
}
];
}
};
});
module.directive('treeviewItem', function () {
return {
restrict: 'E',
templateUrl: "/templates/ui/controls/treeview-item.htm",
replace: true,
scope: {
item: "="
},
link: function (scope, element, attrs) {
console.log("treeview item directive loaded");
}
};
});
Run Code Online (Sandbox Code Playgroud)
Treeview模板:
<div class="sl-treeview">
<ul class="clear" ng-transclude>
<treeview-item ng-repeat="item in items" item="item"></treeview-item>
</ul>
</div>
Run Code Online (Sandbox Code Playgroud)
Treeview项目模板:
<li>
<i class="icon-plus-sign"></i>
<a href="/">
<i class="icon-folder-close"></i>
{{item.text}}
</a>
<!-- This ul is the issue - it crashes the page -->
<ul>
<treeview-item ng-repeat="childitem in item.childitems" item="childitem"></treeview-item>
</ul>
</li>
Run Code Online (Sandbox Code Playgroud)
在treeview指令$scope.items中硬编码用于开发 - 最终我希望这将来自从服务器提取数据的控制器/服务.然而,它代表了我正在寻找的那种基本结构.
当我在没有treeviewItem中的嵌套ul的情况下运行它时,它给了我前三个项目就好了.当我添加ul in以尝试让控件与子项绑定时,它会移动页面并停止工作.
JSFiddle没有嵌套的ul - 工作:
JSFiddle与嵌套ul - 不工作(可能会挂起您的浏览器!):
我应该如何制作一个使用自定义指令和ngRepeat创建可能无限级别的递归的控件?为什么我的方法不起作用?
Ye *_*Liu 15
问题是你试图递归地定义你的指令,当angular尝试编译模板时,它看到了treeview指令,它调用了treeview编译函数,然后它看到了treeviewItem指令,它调用了treeviewItem编译函数,然后它看到了treeviewItem指令,它调用了treeviewItem编译函数,然后它看到了treeviewItem指令,它调用了treeviewItem编译函数...
看到问题?编译函数的调用无法停止.因此,您需要从模板中提取递归定义,但需要$compile手动构建DOM:
module.directive('treeviewItem', function ($compile) {
return {
restrict: 'E',
template: '<li><i class="icon-plus-sign"></i><a href="/"><i class="icon-folder-close"></i>{{item.text}}</a></li>',
replace: true,
scope: {
item: "="
},
link: function (scope, element, attrs) {
element.append($compile('<ul><treeview-item ng-repeat="childitem in item.childitems" item="childitem"></treeview-item></ul>')(scope));
console.log("treeview item directive loaded");
}
};
});
Run Code Online (Sandbox Code Playgroud)
或者,我找到了一个在SO /sf/answers/830272131/上显示树状数据的解决方案.然而,该解决方案使用ngInclude而不是指令.
| 归档时间: |
|
| 查看次数: |
7099 次 |
| 最近记录: |