0

I'm trying to load a template into $templateCache in the module's run block as follows.

angular.module('myapp').run(function($http, $templateCache, $timeout) {
    var templateLocation = 'location/to/template.html';
    $http.get(templateLocation).them(function(response) {
        $templateCache.put(templateLocation, response.data);
    )};
}

This loads the template into templateCache. However, when I try to use it in a directive. It doesn't load because the directive loads before the $http promise gets resolved.

Here is the code for directive

angular.module('myApp').directive('myDirective, directiveFn);
directiveFn.$inject = ["$templateCache"]

function directiveFn($templateCache) {
    var templateLocation = 'location/to/template.html';
    return {
        restrict: 'EA'
        scope: {
            thing1: "="
        }
        template: $templateCache.get(templateLocation)
    }
}

Is there a better way/place to do this?

Guranjan Singh
  • 734
  • 2
  • 7
  • 24
  • What are you trying to accomplish? I'm not sure why you just don't put the template location in templateUrl? – Dvid Silva Apr 09 '16 at 00:52
  • @dvidsilva putting templateUrl causes problems while testing the directive because I'm not using karma. Also, having templates in template loaded cache is better for performance. – Guranjan Singh Apr 09 '16 at 04:08
  • what are you using for testing? also, can't you make it dynamic so it works different on your test vs the browser? – Dvid Silva Apr 13 '16 at 17:58
  • @dvidsilva I'm using jasmine. I'm not sure what you mean by making it dynamic. – Guranjan Singh Apr 13 '16 at 19:41

1 Answers1

1

How about using $templateRequest in your directive? I use this to load a template when the directive is initiated and this allows me to use the templates HTML within the directive.

I am using Typescript and my $templateRequest is a dependency on my directive class, that's why it is in the this scope. this.$templateRequest( 'client/lib/directives/aTemplate.html' ).then( ( html ) => { ... do something } );

A quick look tells me that you can also use it with templatecache. This thread discusses some of that: https://github.com/angular/angular.js/issues/10630

Mattijs
  • 3,265
  • 3
  • 38
  • 35
  • I haven't tried it but it doesn't look like it would solve the problem because I can only do something with `html` after the promise has resolved and by that time directive function would have returned an empty template as in the case of getting template html using `$http().get()` – Guranjan Singh Apr 09 '16 at 04:10
  • 1
    well yes and no, the template loading in the directive will be aSync, yes, but because the directive is loading the template, I and on resolve will do something with the HTML (inject it in its element for example) it should do what you want. No? – Mattijs Apr 09 '16 at 06:53