Angularjs 根据数据结构创建动态菜单无限嵌套循环--指令版

时间:2023-03-09 22:09:17
Angularjs 根据数据结构创建动态菜单无限嵌套循环--指令版

目标:根据数据生成动态菜单,希望可以根据判断是否有子集无限循环下去。

菜单希望的样子是这样的:

Angularjs 根据数据结构创建动态菜单无限嵌套循环--指令版

菜单数据是这样的:

 $scope.expanders = [{
title: 'title1',
link: 'xx/xx',
child:[
{
title: 'child2',
link: 'xx/xx'
},
{
title: 'child3',
link: 'xx/xx',
child:[
{
title: 'child5',
link: 'xx/xx'
}
]
}
]
}, {
title: 'title2',
link: 'xx/xx'
}, {
title: 'title3',
link: 'xx/xx'
}];

那么下面贴下代码,主要是用指令无限递归实现的:

1.js

 var myModule = angular.module('myApp', []);

 myModule.controller('TestController', ['$rootScope', '$scope', function($rootScope, $scope) {
$scope.expanders = [{
title: 'title1',
link: 'xx/xx',
child:[
{
title: 'child2',
link: 'xx/xx'
},
{
title: 'child3',
link: 'xx/xx',
child:[
{
title: 'child5',
link: 'xx/xx'
}
]
}
]
}, {
title: 'title2',
link: 'xx/xx'
}, {
title: 'title3',
link: 'xx/xx'
}];
}]); myModule.directive('accordion', function($compile) {
return {
restrict: 'EA',
replace:true,
scope:{
expander:'=',
child:'='
},
template: "<ul > <li>{{expander.title}}</li></ul>",
link: function(scope,elm) {
if(scope.child){
var html=$compile("<accordion expander='expander' child='expander.child' ng-repeat='expander in child'></accordion>")(scope);
elm.append(html)
} }
};
});

1.html

 <body ng-app="myApp">
<section ng-controller="TestController">
<accordion expander='expander' child='expander.child' ng-repeat='expander in expanders'>
</accordion>
</section>
</body>