我从角度jsand开始我想在angularjs中构建一个带有指令递归的树视图。 为此,我基于这个例子:
并看到我的代码:
模板:
<aside id="left-panel">
<nav>
<treeview></treeview>
</nav>
</aside>
和两个指令:
树状
angular.module('app').directive('treeview', function()
{
return {
restrict: 'E',
template: '<div class="sl-treeview">' +
'<ul ng-transclude>' +
'<treeview-item ng-repeat="item in items" item="item"></treeview-item>' +
'</ul>' +
'</div>',
replace: true,
transclude: true,
scope: {
},
link: function(scope, element, attrs)
{
console.log('treeview directive loaded');
},
controller: function($scope, $rootScope)
{
$rootScope.depth = 0;
$scope.items = $rootScope.modules.submodules;
}
};
});
并查看$ scope.items值:
[{
id: 2,
name: 'Modules',
moduleStandardId: 2,
applicationId: 1,
picto: 'fa fa-cubes',
color: '#68DB62',
functions: [],
submodules: [
{
id: 3,
name: 'Module',
moduleStandardId: 2,
applicationId: 1,
picto: 'fa fa-cube',
color: '#60C8E5',
functions: [
{
id: 1,
name: 'CreateModule',
title: 'CreateModule',
description: 'Créer un module',
moduleId: 3
}
],
submodules: []
},
{
id: 4,
name: 'Fonction',
moduleStandardId: 2,
applicationId: 1,
picto: 'fa fa-gears',
color: '#F20E0E',
functions: [
{
id: 1,
name: 'CreateFunction',
title: 'CreateFunction',
description: 'Créer une fonction pour un module',
moduleId: 4
}
],
submodules: []
}]
和treeview-item:
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>
我测试了不同的东西:
我不明白为什么$ compile不能正常工作...... 在此先感谢您的帮助:)
最后,我认为这是我的转换,哪些不能工作