gpt4 book ai didi

javascript - AngularJS - 递归指令不起作用(无限循环)

转载 作者:行者123 更新时间:2023-12-03 08:22:27 24 4
gpt4 key购买 nike

我需要创建一个能够处理多个(不是确切数量)级别的子菜单的菜单

MainMenu.js(包含带有所有菜单项的菜单属性)

class MainMenu {

// @ngInject
constructor() {


this.menu = {
name: 'Main menu',
list: [
{
name: 'Sub menu lvl 1',
list: [
{
name: 'Sub menu lvl 2',
list: [
{
name: 'Sub menu lvl 3'
}
]
}
]
}
]
}



}
}

export default function () {
return {
scope: {},
templateUrl: 'path/to/MainMenu.tpl.html',
replace: true,
controller: MainMenu,
controllerAs: 'mainMenuCtrl'
};
};
<小时/>

这是模板 html 文件 (MainMenu.tpl.html)

<div>
<nav id="menu" class="cm-menuwrapper">
<ul class="cm-menu">
<li ng-repeat="menuItem in mainMenuCtrl.menu.list">
<a class="cursor-pointer" ng-click="mainMenuCtrl.someMethod(menuItem)"><span>{{menuItem.name}}</span></a>
<sub-menu menu-item="menuItem" ng-if="menuItem.list"></sub-menu>
</li>
</ul>
</nav>
</div>

子菜单.js

class SubMenu {

// @ngInject
constructor() {

}


}

export default function () {
return {
scope: {},
templateUrl: 'path/to/SubMenu.tpl.html',
replace: true,
controller: SubMenu,
controllerAs: 'subMenuCtrl',
bindToController: {
menuItem : "="
}
};
};
<小时/>

子菜单html模板文件(SubMenu.tpl.html)

<ul class="cm-submenu">
<li ng-repeat="submenu in subMenuCtrl.menuItem.list" ng-class="submenu.itemClass">
<a class="cursor-pointer" ng-click="subMenuCtrl.someMethod(submenu)"><span>{{submenu.name}}</span></a>
<sub-menu menu-item="submenu" ng-if="submenu.list"></sub-menu>
</li>
</ul>

如您所见,我已放置 <sub-menu ....> directivve 到 SubMenu.tpl.html 中,这似乎导致某种无限循环。浏览器卡在空白页面并且消耗内存和CPU。

对此问题有什么建议吗?

最佳答案

您必须在 Angular 的初始编译中隐藏子指令。在链接函数中动态添加递归子菜单。这里是修改后的SubMenu.js:

/* @ngInject */ 
function submenuDirective($compile) {
return {
scope: {},
templateUrl: 'path/to/SubMenu.tpl.html',
replace: true,
controller: SubMenu,
controllerAs: 'subMenuCtrl',
bindToController: {
menuItem : "="
},
link: function(scope, elm) {
const submenuNode = elm.find('.cm-submenu-list');
submenuNode.append('<sub-menu menu-item="submenu" ng-if="submenu.list"></sub-menu>');
$compile(submenuNode)(scope);
}
};
};

并且不要忘记将包装器添加到模板中:

<ul class="cm-submenu">
<li ng-repeat="submenu in subMenuCtrl.menuItem.list" ng-class="submenu.itemClass">
<a class="cursor-pointer" ng-click="subMenuCtrl.someMethod(submenu)"><span>{{submenu.name}}</span></a>
<!-- submenu items will be rendered here later -->
<div class="cm-submenu-list"></div>
</li>
</ul>

关于javascript - AngularJS - 递归指令不起作用(无限循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33695023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com