gpt4 book ai didi

javascript - 在 AngularJS 指令中初始化 Zurb Foundation 5

转载 作者:数据小太阳 更新时间:2023-10-29 04:13:45 24 4
gpt4 key购买 nike

我创建了三个 plunkr 来说明我的问题。我正在尝试创建一个 AngularJS 指令,它将初始化基础并将必要的 javascript 应用于加载的模板。起初我试图使用 ngInclude 将 Foundation 5 导航栏添加到我网站的所有页面。当 html 直接应用于部分时,顶部栏按预期工作。当在指令中添加 html 时,例如 ngInclude,顶部栏将失去其所有功能。我怀疑这是因为在指令添加模板后基础没有得到初始化。作为解决方案,我创建了一个自定义指令来初始化基础并编译 html 模板。以我的方式初始化基础会卡住应用程序。有人对此有解决方案吗?

尝试在不借助 Angular UI 的情况下实现这一目标。

示例 1:HTML 直接应用于 View 。按预期工作,当您单击下拉菜单时,将显示页面。

http://plnkr.co/edit/aQc6j2W9MpRuJo822gAF?p=preview

示例2:ngInclude 用于加载模板到dom。没有实现任何功能,当您单击下拉菜单时没有任何反应。

http://plnkr.co/edit/fSS3FfYKFilMXsIkYUHg?p=preview

示例 3:创建单独的指令来替换 ngInclude,它将初始化基础、编译并将模板加载到 DOM。无法提供 plunkr,因为它会卡住,但这是代码。

.directive('testdirective', function($compile) {
return {
restrict: 'AE',
templateUrl: 'partials/includes/nav.html',
link: function(scope, element, attrs) {
$compile($(document).foundation())(scope);
}
}
})

部分应用者:

<div testdirective></div>

最佳答案

这样做:

link: function(scope, element, attrs) {
$compile(element.contents())(scope);
$(document).foundation();
}

如果编译元素本身,就会创建一个无限循环:

$编译(元素)(范围);//失败

始终确保只编译元素的内容:

$compile(element.contents())(范围);//赢

看来您正在编译整个文档并创建无限循环。

你也许可以这样做:

templateUrl: 'partials/includes/nav.html',
compile: function() {
$(document).foundation();
}

因为模板会自动编译,所以你不必手动编译。

注意:最好的做法是注入(inject)和使用 Angular 的 $document,它是 document 的包装器,有助于测试。 $($document).foundation();

关于javascript - 在 AngularJS 指令中初始化 Zurb Foundation 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21121514/

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