簡介
第一次使用模板,它被加載到模板緩存中褂删,以便快速檢索颅停。你可以直接將模板標簽加載到緩存中惫搏,或者通過$templateCache服務(wù)。
通過script標簽:
<script type=”text/ng-template” id=”template.html”>
<p>This is the content of the template</p>
</script>
備注:script標簽?zāi)0宀恍枰谖臋n頭部蚕涤。但他必須在$rootElement下筐赔,不然模板將會被忽略。
通過$templateCache服務(wù):
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
檢索模板后揖铜,只需使用它在您的組件:
myApp.component('myComponent', {
templateUrl: 'templateId.html'
});
或者通過$templateCache獲取它
$templateCache.get('templateId.html')
應(yīng)用
當(dāng)您在應(yīng)用程序中引用模板時茴丰,Angular-JS通常會從服務(wù)器延遲加載模板(通過ng-include,路由配置或其他機制)天吓。Angular緩存每個模板的源代碼贿肩,以便后續(xù)引用不需要其他服務(wù)器請求。但是龄寞,如果您的應(yīng)用程序被分成許多小組件汰规,那么初始加載過程可能涉及大量額外的服務(wù)器請求。
grunt-html2js或grunt-angular-templates
等插件將一組模板轉(zhuǎn)換為JavaScript物邑,并將它們組裝成一個Angular模塊溜哮,該模塊在加載模塊時直接填充緩存。您可以將此模塊與主應(yīng)用程序代碼連接色解,以便Angular不需要進行任何其他服務(wù)器請求來初始化應(yīng)用程序茂嗓。
使用插件編譯后示例:
//template-a.html+template-b.html => ab-tpl.js
//將兩個html合并,轉(zhuǎn)化為js
angular.module('templateModule', []).run(['$templateCache', function ($templateCache) {
"use strict";
$templateCache.put("global_appfooter.html","<div>template-a.html</div>");
$templateCache.put("global_detailcard.html","<div>template-b.html</div>");
}]);