我正在尝试使用 $templateCache
并具有以下代码:
我的所有模板都编译在 templates.js
中:
angular.module("gm.templates", []).run(["$templateCache", function($templateCache) {$templateCache.put("/app/app-mc3.html","<div class=.......
我的主 app.js
像这样加载它
angular.module('app', ['ui.router', 'ct.ui.router.extras', 'gm.templates',.....
我在加载app.js
之前加载了templates.js
文件,但是当我尝试使用$templateCache
时在我的一项服务中,它已定义但为空,这意味着尚未加载任何模板。
以下是我的应用程序中 $templateCache.info()
的一些日志。
ClientService-0.1.5.js:2 Object {id: "templates", size: 0}
ClientService-0.1.5.js:27 /app/app-mc3.html
ClientService-0.1.5.js:28 Object {} // console.log($templateCache)
ClientService-0.1.5.js:29 undefined // Trying to find a specific template in the $templateCache
ClientService-0.1.5.js:2 Object {id: "templates", size: 72}
app-0.1.5.js:3 Object {id: "templates", size: 72}
所以,我的理解是模板可用,但一开始就不可用。看起来这是一个依赖顺序问题。
Angular 子模块的 module.run()
是否在我的应用程序的主入口点之前执行?我感觉注入(inject)是正确完成的,但是 gm.templates
run() 方法是以某种方式对我的服务异步完成的。如何在需要之前强制执行子模块.run()?
最佳答案
如果您想在应用程序运行之前访问模板列表,可以将它们附加到窗口对象。
您可以通过配置 grunt/gulp 任务来实现这一点。 (喝一口咖啡)
然后,您将在 window.gtTemplates
对象中拥有所有模板,并可以在您的服务中使用它们。请注意,$templateCache
也将像以前一样填充。
TEMPLATE_HEADER = 'window.gmTemplates = {};'
TEMPLATE_BODY = 'window.gmTemplates["<%= url %>"] = "<%= contents %>";'
TEMPLATE_FOOTER = 'angular.module("<%= module %>").run(["$templateCache", function($templateCache) {
Object.keys(window.gmTemplates).forEach(function(url) {
$templateCache.put(url, window.gmTemplates[url])
})
}]);'
gulp.task 'template', ->
gulp.src([
'src/**/*.html'
'!src/index.html'
])
.pipe(templateCache(
root: '/'
module: 'app'
templateHeader: TEMPLATE_HEADER
templateBody: TEMPLATE_BODY
templateFooter: TEMPLATE_FOOTER
))
.pipe(gulp.dest('dist/src/'))
关于javascript - Angular 主模块依赖于 $templateCache.run() (子模块),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34988551/