$templateCache, $templateRequest


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ù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • AngularJS是什么?AngularJs(后面就簡(jiǎn)稱ng了)是一個(gè)用于設(shè)計(jì)動(dòng)態(tài)web應(yīng)用的結(jié)構(gòu)框架。首先,它是...
    200813閱讀 1,788評(píng)論 0 3
  • 概要 64學(xué)時(shí) 3.5學(xué)分 章節(jié)安排 電子商務(wù)網(wǎng)站概況 HTML5+CSS3 JavaScript Node 電子...
    阿啊阿吖丁閱讀 9,874評(píng)論 0 3
  • AngularJSAngularJS 是一個(gè) MV* 框架, 最適于開發(fā)客戶端的單頁(yè)面應(yīng)用。它不是個(gè)功能庫(kù),...
    一直以來都很好閱讀 955評(píng)論 0 0
  • 面試題一:https://github.com/jimuyouyou/node-interview-questio...
    R_X閱讀 1,775評(píng)論 0 5
  • # Ajax標(biāo)簽(空格分隔): 筆記整理---[TOC]### 從輸入網(wǎng)址開始:- 在學(xué)習(xí)ajax之前,你應(yīng)該先了...
    V8閱讀 344評(píng)論 1 0

友情鏈接更多精彩內(nèi)容