javascript 如何使用 AngularJS $templateCache.get()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24757917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use AngularJS $templateCache.get()?
提问by HoffZ
I need to cache some HTML files when my Angular controller initializes.
当我的 Angular 控制器初始化时,我需要缓存一些 HTML 文件。
According to Angular $templateCache documentationI can add HTML templates to Angular with:
根据 Angular $templateCache 文档,我可以使用以下命令将 HTML 模板添加到 Angular:
$templateCache.get('templateId.html')
But I can't get this to work. I've tried to get the template file within the controller and within the module run() function (Plunker). But I can see in the network console that the template is not fetched.
但我无法让它发挥作用。我试图在控制器和模块 run() 函数(Plunker)中获取模板文件。但是我可以在网络控制台中看到没有获取模板。
app.run(function($templateCache) {
$templateCache.get('templ.html');
});
What am I doing wrong?
我究竟做错了什么?
回答by Francis Stalin
You have to fetch html using http request then you can store it in template cache. For example:
您必须使用 http 请求获取 html,然后才能将其存储在模板缓存中。例如:
$http.get('templ.html', {
cache: $templateCache
}).then(function(result) {
console.log(result);
});
回答by ZooZ
You can use $templateRequest to fetch the template.
您可以使用 $templateRequest 来获取模板。
The $templateRequest service runs security checks then downloads the provided template using $http and, upon success, stores the contents inside of $templateCache. If the HTTP request fails or the response data of the HTTP request is empty, a $compile error will be thrown (the exception can be thwarted by setting the 2nd parameter of the function to true). Note that the contents of $templateCache are trusted, so the call to $sce.getTrustedUrl(tpl) is omitted when tpl is of type string and $templateCache has the matching entry.
$templateRequest 服务运行安全检查,然后使用 $http 下载提供的模板,并在成功后将内容存储在 $templateCache 中。如果 HTTP 请求失败或 HTTP 请求的响应数据为空,则会抛出 $compile 错误(可以通过将函数的第二个参数设置为 true 来阻止异常)。请注意,$templateCache 的内容是可信的,因此当 tpl 是 string 类型且 $templateCache 具有匹配条目时,将省略对 $sce.getTrustedUrl(tpl) 的调用。
Documentation: https://docs.angularjs.org/api/ng/service/$templateRequest
文档:https: //docs.angularjs.org/api/ng/service/$templateRequest