Angularjs 根据数据结构创建动态菜单无限嵌套循环--指令版
目标:根据数据生成动态菜单,希望可以根据判断是否有子集无限循环下去。
菜单希望的样子是这样的:
菜单数据是这样的:
1 $scope.expanders = [{ 2 title: 'title1', 3 link: 'xx/xx', 4 child:[ 5 { 6 title: 'child2', 7 link: 'xx/xx' 8 }, 9 { 10 title: 'child3', 11 link: 'xx/xx', 12 child:[ 13 { 14 title: 'child5', 15 link: 'xx/xx' 16 } 17 ] 18 } 19 ] 20 }, { 21 title: 'title2', 22 link: 'xx/xx' 23 }, { 24 title: 'title3', 25 link: 'xx/xx' 26 }];
那么下面贴下代码,主要是用指令无限递归实现的:
1.js
1 var myModule = angular.module('myApp', []); 2 3 myModule.controller('TestController', ['$rootScope', '$scope', function($rootScope, $scope) { 4 $scope.expanders = [{ 5 title: 'title1', 6 link: 'xx/xx', 7 child:[ 8 { 9 title: 'child2', 10 link: 'xx/xx' 11 }, 12 { 13 title: 'child3', 14 link: 'xx/xx', 15 child:[ 16 { 17 title: 'child5', 18 link: 'xx/xx' 19 } 20 ] 21 } 22 ] 23 }, { 24 title: 'title2', 25 link: 'xx/xx' 26 }, { 27 title: 'title3', 28 link: 'xx/xx' 29 }]; 30 }]); 31 32 myModule.directive('accordion', function($compile) { 33 return { 34 restrict: 'EA', 35 replace:true, 36 scope:{ 37 expander:'=', 38 child:'=' 39 }, 40 template: "<ul > <li>{{expander.title}}</li></ul>", 41 link: function(scope,elm) { 42 if(scope.child){ 43 var html=$compile("<accordion expander='expander' child='expander.child' ng-repeat='expander in child'></accordion>")(scope); 44 elm.append(html) 45 } 46 47 } 48 }; 49 });
1.html
1 <body ng-app="myApp"> 2 <section ng-controller="TestController"> 3 <accordion expander='expander' child='expander.child' ng-repeat='expander in expanders'> 4 </accordion> 5 </section> 6 </body>