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.jshtml

 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.htmlapp

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>
相關文章
相關標籤/搜索