使用ng-include和模板缓存

des*_*lee 3 angularjs

我正在开发角js.以前,我使用ng-include和url.但是我怎么能将url指向templatecache?

<ng-include
  src="string"
  [onload="string"]
  [autoscroll="string"]>
...
</ng-include>
Run Code Online (Sandbox Code Playgroud)

Ron*_*don 15

模板缓存使用密钥来标识缓存的元素,因此您可以使用密钥.

  $templateCache.put('MY KEY', 'Cached content');
Run Code Online (Sandbox Code Playgroud)

并在HTML中:

<ng-include src="'MY KEY'"></ng-include>
Run Code Online (Sandbox Code Playgroud)

$ templateCache的 AngularJS文档中查看它.


gau*_*430 5

有两种方式:

在标记中:

将您的模板指定为脚本标签:

<script type="text/ng-template" id="templateId.html">
  <p>This is the content of the template</p>
</script>
Run Code Online (Sandbox Code Playgroud)

(这应该是 your 的后代,ng-app换句话说,它应该在ng-app标记内的某处指定)

这将自动缓存模板。

在代码中:

var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
  $templateCache.put('templateId.html', 'This is the content of the template');
});
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,您都可以像这样获取缓存的模板:

<div ng-include=" 'templateId.html' "></div>
Run Code Online (Sandbox Code Playgroud)

或者

$templateCache.get('templateId.html')
Run Code Online (Sandbox Code Playgroud)