layout: post
title: Angular@1.4.3 中文 API 服務(wù)篇 $templateCache & $templateRequest
desc: '關(guān)于模板的兩個(gè)服務(wù),緩存和請(qǐng)求'
categories: jekyll update
$templateCache
- ng模塊中的服務(wù)
在模板第一次被引用時(shí),它會(huì)被載入到模板緩存中以便快速的檢索。你可以直接使用一個(gè)script標(biāo)簽來添加一個(gè)
模板,或者直接通過 $templateCache 服務(wù)來達(dá)到相同的效果。
通過 script 標(biāo)簽添加:
html
<script type="text/ng-template" id="templateId.html">
<p>This is the content of the template</p>
</script>
注意:script 標(biāo)簽包含的模板并不需要 document 的頭部,但它必須是 $rootElement 的
后代(IE,帶有 ng-app 屬性的元素),否則這個(gè)模板將被忽略掉。
通過$templateCache 服務(wù)添加:
javascript
var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
$templateCache.put('templateId.html', 'This is the content of the template');
});
在檢索模板之后,你就可以在你的 HTML 里輕松的使用了。
html
<div ng-include=" 'templateId.html' "></div>
或者通過 Javascript 得到它 :
javascript
$templateCache.get('templateId.html')
請(qǐng)看 $cacheFactory.
$templateRequest
- ng模塊中的服務(wù)
$templateRequest 服務(wù)
$templateRequest 服務(wù)使用 $http 服務(wù)下載模板,并在之后進(jìn)行安全檢測(cè)。如果成功,
則內(nèi)容會(huì)被存儲(chǔ)到 $templateCache 中。如果HTTP請(qǐng)求失敗或者該請(qǐng)求的響應(yīng)數(shù)據(jù)為空,
會(huì)拋出一個(gè)編譯($compile)錯(cuò)誤(這個(gè)行為可以通過將函數(shù)的第二個(gè)參數(shù)設(shè)置為 true 來阻止)。
需要注意的是,$templateCache 的內(nèi)容是可以信任的,因此當(dāng) tpl 是以字符串形式出現(xiàn)的時(shí)候,
或者通過 $templateCache 作為入口時(shí),是可以不必去調(diào)用 $sce.getTrustedUrl(tpl) 來驗(yàn)證的。
用法
$templateRequest(tpl, [ignoreRequestError]);
參數(shù)
| 參數(shù) | 形式 | 詳細(xì) |
|---|---|---|
| tpl |
string TrustedResourceUrl
|
HTTP 請(qǐng)求的模板路徑(URL) |
| ignoreRequestError (可選) | boolean |
是否忽略請(qǐng)求失敗或者模板為空的情況 |
返回
promise - 一個(gè)表示通過給定的路徑請(qǐng)求得到的 HTTP 相應(yīng)數(shù)據(jù)的 promise
屬性
totalPendingRequests - number - 所有被需求下載模板的總數(shù)