gpt4 book ai didi

javascript - 使用 NgInclude 加载 AngularJS 组合指令模板

转载 作者:行者123 更新时间:2023-11-28 07:36:40 24 4
gpt4 key购买 nike

我想将所有指令模板包含在一个文件中,以减少加载指令较多的页面所需的 HTTP 请求数量。

我有这个指令

angular.module('bwDirectives', [])
.directive('bwInfoCard', function () {
return {
restrict: 'E',
transclude: false,
replace: true,
scope: { title: '=' },
templateUrl: "one-template",
};
})

如果我像这样内联指定模板,那么它会正确加载指令模板:

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8" />
<title>Directive Test Fixture</title>
<link rel="stylesheet" href="../Style.css" type="text/css" />
<script src="../../../Libraries/angular.min.js"></script>
<script src="../Widget.js"></script>
<script src="./Fixture.js"></script>
</head>
<body ng-app="BaseWidgetFixtures">
<h1>Base Info Card</h1>
<script type="text/ng-template" id="one-template">
<div>This is first template</div>
</script>
<script type="text/ng-template" id="two-template">
<div>This is second template</div>
</script>
<div ng-controller="InfoCardFixture">
<bw-info-card title="title"></bw-info-card>
</div>
</body>
</html>

如果我尝试通过 NgIninclude 包含模板,则会失败。我猜它会尝试在执行 NgInclude 之前加载指令模板(即使它位于文件的前面)。页面上包含正确的脚本标记。

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8" />
<title>Directive Test Fixture</title>
<link rel="stylesheet" href="../Style.css" type="text/css" />
<script src="../../../Libraries/angular.min.js"></script>
<script src="../Widget.js"></script>
<script src="./Fixture.js"></script>
</head>
<body ng-app="BaseWidgetFixtures">
<h1>Base Info Card</h1>
<div ng-include src="'templates.html'"></div>
<div ng-controller="InfoCardFixture">
<bw-info-card title="title"></bw-info-card>
</div>
</body>
</html>

是否有我遗漏的东西,或者您不能 NgIninclude 与指令一起使用的模板吗?

谢谢。

最佳答案

看看这篇讨论,Pete Bacon Darwin 解释了指令的链接/编译顺序。 https://groups.google.com/forum/#!topic/angular/3HsNz4ncnYA/discussion 。您可能可以重新排列 html 来使其正常工作,但这并不是 ng-include 真正的目的。我建议使用类似 angular-templatecache 的东西如果您不想使用 AJAX 加载模板。

关于javascript - 使用 NgInclude 加载 AngularJS 组合指令模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28521495/

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