angularJs $templateCache

來源:互聯網
上載者:User

標籤:scope   return   服務   proc   javascrip   它的   技巧   優秀   檔案內容   

  模板載入後,AngularJS會將它預設緩衝到 $templateCache 服務中。在實際生產中,可以提前將模板緩衝到一個定義模板的JavaScript檔案中,這樣就不需要通過XHR來載入模板了

  $templateCache 服務允許 $http 服務緩衝經過XHR的模板請求,這樣它們就只會被請求一次。當一個模板被取到了,它的內容就會儲存在 $templateCache 中,用模板路徑作鍵。例如,當擷取下面的執行個體指令時,它會請求 templateUrl 並且把模板的內容放在 $templateCache 中:

1 angular.module(‘myApp‘)2     .directive(‘notification‘, function($timeout) {3         return {4             restrict: ‘A‘,5             scope: { ngModel: ‘=‘ },6             templateUrl: ‘views/templates/notification.html‘,7 }});

$templateCache 會 把 這 個 模 板 的 內 容 保 持 在 $templateCache(‘views/templates/notification.html‘) 中。如果已經預先在 $templateCache 中存放了測試所需的指令檔案內容,就可以使用 $templateCache 來阻止在指令的單元測試中再產生請求。可以使用優秀的 karma-ng-html2js-preprocessor 包來把模板轉換成可在測試中使用的Angular模組。

利用 $templateCache
  在生產中部署應用時,我們都希望應用的載入儘可能快,以及儘可能做出響應。使用XHR載入模板可能會導致Web應用緩慢或者有卡頓的感覺。可以通過將模板封裝為JavaScript檔案,然後連同應用程式的其他部分一起傳輸的方式偽造模板緩衝載入,而不是通過XHR提模數板。關於如何有效地封裝模板的詳細資料,請參考 $templateCache 工具: grunt-angular-templates 。

  預設情況下,Angular無法從本地 $tempalteCache 中找到模板時,會通過XHR提模數板。當XHR請求很慢,或者模板很大時,它可能會對應用的使用者體驗造成很大的負面影響。
  你可以通過“偽造” $templateCache 已經被填充的方式來避免這一延遲,這樣Angular就不必從遠程載入模板。可以在JavaScript中手動實現這個技巧,就像這樣:

1 angular.module(‘myApp‘,[])2     .run(function($templateCache) {3         $templateCache.put(‘home.html‘, ‘This is the home template‘);4 });

  現在,當Angular需要提取名為home.html的模板時,它會在 $templateCahce 中找到它,而無需從伺服器提取。

 

angularJs $templateCache

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.