【问题标题】:How to use AngularJS $templateCache.get()?如何使用 AngularJS $templateCache.get()?
【发布时间】:2014-09-05 15:09:45
【问题描述】:

当我的 Angular 控制器初始化时,我需要缓存一些 HTML 文件。

根据 Angular $templateCache documentation 我可以将 HTML 模板添加到 Angular:

$templateCache.get('templateId.html')

但我无法让它工作。我试图在控制器和模块 run() 函数 (Plunker) 中获取模板文件。但是我可以在网络控制台中看到没有获取模板。

app.run(function($templateCache) {
  $templateCache.get('templ.html');
});

我做错了什么?

【问题讨论】:

  • 我误解了文档。我认为 get() 是“HTTP GET 这个模板 URL”。但这只是一个getter方法。要使用 HTTP GET 模板为 $templateCache 提供数据,请参阅所选答案。

标签: javascript angularjs templates caching


【解决方案1】:

您必须使用 http 请求获取 html,然后才能将其存储在模板缓存中。例如:

$http.get('templ.html', {
    cache: $templateCache
}).then(function(result) {
    console.log(result);
});

Updated plunker code here

【讨论】:

  • 使用$templateRequest而不是$http不是更好吗,因为它会自动以角度可预测的方式进行异步模板获取+缓存?
【解决方案2】:

您可以使用 $templateRequest 来获取模板。

$templateRequest 服务运行安全检查,然后使用 $http 下载提供的模板,并在成功后将内容存储在 $templateCache 中。如果 HTTP 请求失败或者 HTTP 请求的响应数据为空,则会抛出 $compile 错误(可以通过将函数的第 2 个参数设置为 true 来阻止该异常)。注意 $templateCache 的内容是可信的,所以当 tpl 是 string 类型并且 $templateCache 有匹配的条目时,对 $sce.getTrustedUrl(tpl) 的调用被省略。

文档:https://docs.angularjs.org/api/ng/service/$templateRequest

【讨论】:

    猜你喜欢
    • 2016-09-26
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 2017-09-16
    相关资源
    最近更新 更多