javascriptangularjsangular-templatecache

Angular main module depends on $templateCache.run() (submodule)


I'm trying to use $templateCache and have the following code:

All my templates are compiled in a templates.js:

angular.module("gm.templates", []).run(["$templateCache", function($templateCache) {$templateCache.put("/app/app-mc3.html","<div class=.......

My main app.js loads it like this

angular.module('app', ['ui.router', 'ct.ui.router.extras', 'gm.templates',.....

I'm loading the templates.js file before to load the app.js, but when I try to use the $templateCache in one of my services, it's defined but empty, meaning no template have been loaded yet.

Here are some logs of $templateCache.info() in my app.

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}

So, what I understand is that the templates are available but not at the beginning. It looks like it's a dependency order issue.

Does the module.run() of angular submodules is executed before the main entry point of my app? I have the feeling the injection is done correctly, but the gm.templates run() method is done asynchronously somehow to my services. How can I force the submodule.run() to be executed before I need it?


Solution

  • If you want to access the list of your templates before your app is running, you can attach them to a window object.

    You can do so by configuring the grunt/gulp task. (gulp coffee here)

    Then you'll have all your templates in the window.gtTemplates object and can use them in your service. Note that $templateCache will also be populated as before.

    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/'))