我正在尝试使用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) {}
}
}
]);
我的控制器:
app.controller('myController', ['$scope', function (ng) {
ng.menu = [{
Id : 1,
Nome : "Contact",
Children : [{
Nome : "Testing",
Children : []
}]
}];
}
]);
以下是我使用它的方式:
<navigation menu="menu"></navigation>
答案 0 :(得分:15)
这里有两件事:
$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);
});
};
}
};
我在这里拼凑了一些帮助:Recursion in Angular directives
更新:http://jsfiddle.net/mikeeconroy/Z6sG9/2/解决多个根元素问题
答案 1 :(得分:1)
动态,递归导航菜单(导航栏),使用动态数据和Angular&amp;引导。
http://plnkr.co/edit/YqGcmcH6VQqr3rxOswnb
<div ng-app="headerMenuApp">
<div ng-controller="headerMenuListController">
<nav id="headerNavigationMenuContainer" class="navbar navbar-default">
<div class="container-fluid">
<!-- Non-collapsing right-side menu items -->
<div class="navbar-header pull-right">
<ul class="nav pull-left navbar-nav text-nowrap">
<li class="dropdown pull-right">
<a href="#" class="dropdown-toggle navbar-icon" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-question-circle"></i> Help <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="#">Live Chat</a></li>
<li><a href="#">Help Topics</a></li>
</ul>
</li>
</ul>
</div>
<!-- Collapsing left-side menu items -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed pull-left" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Logo</a>
</div>
<div id="navbar" class="collapse navbar-collapse" ng-class="!navCollapsed && 'in'">
<ul class="nav navbar-nav text-nowrap">
<leaf ng-repeat='leaf in tree' leaf='leaf'></leaf>
</ul>
</div>
</div>
</nav>
</div>
</div>