使用ng-include与模板缓存

5

我正在开发AngularJS。之前,我使用ng-include和URL一起使用。但是如何将URL指向TemplateCache呢?

<ng-include
  src="string"
  [onload="string"]
  [autoscroll="string"]>
...
</ng-include>
2个回答

18

模板缓存使用一个键来标识缓存元素,因此你可以使用该键。

  $templateCache.put('MY KEY', 'Cached content');

并且在HTML中:

<ng-include src="'MY KEY'"></ng-include>

请参见AngularJS文档的$templateCache部分。


模板缓存键的简单好例子。 - cnorthfield
1
这个答案帮助我更好地理解了templateCache的工作原理,以及键不必看起来像文件名。 - Christiaan Westerbeek
如何设置模板的URL,而不是直接在put函数中添加HTML? - Mohamad Al Asmar
没有必要添加模板的URL,缓存的目的是为了防止HTTP请求获取模板。如果您想预先加载所有模板,可以使用$http服务来获取模板,然后将它们存储在$templateCache中。 - Ron Dadon

5

有两种方法:

在标记中:

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

<script type="text/ng-template" id="templateId.html">
  <p>This is the content of the template</p>
</script>

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

这将自动缓存模板。

代码示例:

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

无论哪种情况,您都可以像这样获取缓存的模板:
<div ng-include=" 'templateId.html' "></div>

或者

$templateCache.get('templateId.html')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接