【问题标题】:Angular main module depends on $templateCache.run() (submodule)Angular 主模块依赖于 $templateCache.run() (子模块)
【发布时间】:2016-01-26 01:14:45
【问题描述】:

我正在尝试使用$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}

所以,我的理解是模板可用但一开始不可用。看起来是依赖顺序问题。

角度子模块的module.run() 是否在我的应用程序的主入口点之前执行?我感觉注入是正确完成的,但是 gm.templates run() 方法以某种方式对我的服务异步完成。如何在我需要之前强制执行 submodule.run()?

【问题讨论】:

  • 请张贴使用“/app/app-mc3.html”的代码。 $templateCache 是同步的,submodule.runmodule.run 之前执行。
  • @estus 我在服务中使用它。这是要点gist.github.com/Vadorequest/39b66554769d34a68b50
  • @estus 确实,submodule.runmodule.run 之前执行,但submodule.runmodule.config 之前没有执行,所以所有 gm.templates 都在之后填充我的应用已启动。

标签: javascript angularjs angular-templatecache


【解决方案1】:

如果您想在应用运行之前访问模板列表,可以将它们附加到窗口对象。

您可以通过配置 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/'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-17
    相关资源
    最近更新 更多