[英]Loading AngularJS combined directive templates with NgInclude
我想將所有指令模板都包含在一個文件中,以減少加載指令繁重頁面所需的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>
如果我嘗試通過NgInclude包含模板,則會失敗。 我猜想它會在執行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>
是否有我缺少的東西,或者您是否可以將NgInclude模板與指令一起使用?
謝謝。
看一下這個討論,Pete Bacon Darwin在其中解釋了指令鏈接/編譯的順序。 https://groups.google.com/forum/#!topic/angular/3HsNz4ncnYA/discussion 。 您可能可以重新排列html來使其正常工作,但這並不是ng-include
真正要做的。 如果您不想用AJAX加載模板,我建議使用諸如angular-templatecache之類的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.