递归菜单指令

Wea*_*lBr 6 angularjs angularjs-directive

我正在尝试使用angularJS做一个递归菜单,但我不断收到错误:超出最大调用堆栈大小

我的指示:

angular.module("application").directive("navigation", [function () {
            return {
                restrict : 'E',
                replace : true,
                scope : {
                    menu : '='
                },
                template : '<ul><navigation-item ng-repeat="item in menu" submenu="item"></navigation-item></ul>',
                link : function ($scope, elem, attrs) {}
            }
        }
    ]);


angular.module("application").directive("navigationItem", [function () {

            return {
                restrict : 'E',
                replace : true,
                scope : {
                    submenu : '='
                },
                template : '<li>{{ submenu }}<navigation menu="submenu.Children"></navigation></li>',
                link : function ($scope, elem, attrs) {}
            }
        }
    ]);
Run Code Online (Sandbox Code Playgroud)

我的控制器:

app.controller('myController', ['$scope', function (ng) {
        ng.menu = [{
            Id : 1,
            Nome : "Contact",
            Children : [{
                Nome : "Testing",
                Children : []
            }]
        }];
    }
]);
Run Code Online (Sandbox Code Playgroud)

这是我使用它的方式:

<navigation menu="menu"></navigation>

http://jsfiddle.net/7sq3n/

m.e*_*roy 15

这里有两件事:

  1. 您不需要2个指令
  2. 我怀疑你需要使用指令的编译功能才能使它工作,因为你在自己的模板中使用指令本身,你还需要使用注入 $compile

我已经ngIf在模板中使用了该指令,您没有必要我只是想让您知道并警告您需要使用AngularJS 1.1.5+才能使用该指令.

这是我工作的JSFiddle:http://jsfiddle.net/mikeeconroy/7sq3n/6/

.directive("navigation", ['$log','$compile',function ($log,$compile) {

    return {
        restrict: 'E',
        replace: true,
        scope: {
            menu: '='
        },
        template: '<ul><li ng-repeat="item in menu">{{item.Name}}<span ng-if="item.Children.length > 0"><navigation menu="item.Children"></navigation></span></li></ul>',
        compile: function (el) {
            var contents = el.contents().remove();
            return function(scope,el){
                $compile(contents)(scope,function(clone){
                    el.append(clone);
                });
            };
        }
    };
Run Code Online (Sandbox Code Playgroud)

我在这里用一点帮助拼凑了这个:Angular指令中的递归

更新:http://jsfiddle.net/mikeeconroy/Z6sG9/2/ 解决多个根元素问题