Javascript 使用递归指令构建树视图
我从angularjs开始,我想用angularjs中的递归指令构建一个树状视图。 为此,我基于以下示例: 请看我的代码: 模板:Javascript 使用递归指令构建树视图,javascript,angularjs,recursion,Javascript,Angularjs,Recursion,我从angularjs开始,我想用angularjs中的递归指令构建一个树状视图。 为此,我基于以下示例: 请看我的代码: 模板: <aside id="left-panel"> <nav> <treeview></treeview> </nav> </aside> 和treeview项目: angular.module('app').directive('treeviewItem', f
<aside id="left-panel">
<nav>
<treeview></treeview>
</nav>
</aside>
和treeview项目:
angular.module('app').directive('treeviewItem', function($compile)
{
return {
restrict: 'E',
template: '<li><a href="">{{item.name}}</a></li>',
replace: true,
scope: {
item: '='
},
link: function(scope, element, attrs)
{
console.log('item');
scope.$watch('item.submodules', function()
{
element.append(
$compile(
'<ul>' +
'<treeview-item ng-repeat="childitem in item.submodules" item="childitem"></treeview-item>' +
'</ul>'
)(scope)
);
});
console.log('treeview item directive loaded');
}
};
});
angular.module('app')。指令('treevieItem',函数($compile)
{
返回{
限制:'E',
模板:“”,
替换:正确,
范围:{
项目:'='
},
链接:函数(范围、元素、属性)
{
console.log('item');
作用域$watch('item.submodules',function()
{
元素.append(
$compile(
“”+
'' +
“
”
)(范围)
);
});
log('treeview item指令loaded');
}
};
});
结果,我得到:
<div class="sl-treeview ng-isolate-scope">
<ul ng-transclude=""></ul>
</div>
我测试了不同的东西:
- 如果我传入指令:是(使用console.log)
- 如果手表工作:是的,我放了一个console.log('lalala'),我有三次'lalala'
- treeview项目中的元素看起来不错
- 这些项不为空
angular.module('app').directive('treeviewItem', function($compile)
{
return {
restrict: 'E',
template: '<li><a href="">{{item.name}}</a></li>',
replace: true,
scope: {
item: '='
},
link: function(scope, element, attrs)
{
console.log('item');
scope.$watch('item.submodules', function()
{
element.append(
$compile(
'<ul>' +
'<treeview-item ng-repeat="childitem in item.submodules" item="childitem"></treeview-item>' +
'</ul>'
)(scope)
);
});
console.log('treeview item directive loaded');
}
};
});
<div class="sl-treeview ng-isolate-scope">
<ul ng-transclude=""></ul>
</div>