0

I want to use $templateCache service to add some html into the cache. In Angular documentation example, it only shows the case of using it in run:

var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
  $templateCache.put('templateId.html', 'This is the content of the template');
});

However, when I am trying to add some templates through myApp config, there seems to be injector error. Is there a way to use templateCache not in RUN?

Thanks

uksz
  • 18,239
  • 30
  • 94
  • 161
  • Are you 100% positive that you cannot inject $templateCache in config? What's the injector error? – mostruash Feb 24 '16 at 08:34
  • Its the Error: $injector:modulerr Module Error – uksz Feb 24 '16 at 08:35
  • 1
    @mostruash $templateCache is a service and cannot be injected into config. You can inject providers only. – hansmaad Feb 24 '16 at 08:35
  • @hansmaad, so only factories may be injected into the config? – uksz Feb 24 '16 at 08:36
  • @uksz providers. Why do you want to add templates in `config`? What's wrong with `run`? – hansmaad Feb 24 '16 at 08:37
  • Oh that makes sense. It was more intuitive for me to include it in config ;) But I guess I was wrong, becasue Run gets executed before config, is that right? – uksz Feb 24 '16 at 08:39
  • `config` is used to configure services (using their providers). They will be created after `config` and then available in `run`. https://docs.angularjs.org/guide/providers#provider-recipe – hansmaad Feb 24 '16 at 08:41
  • Please see this link to add items dynamically into templateCache http://blog.mgechev.com/2013/10/01/angularjs-partials-lazy-prefetching-strategy-weighted-directed-graph/ – Naga Sandeep Feb 24 '16 at 08:44

2 Answers2

2

run is the correct place to use the $templateCache. Since $templateCache is a service, it's not accessible in the configuration phase, because it hasn't been created yet. config is used to configure services (like $templateCache) using their providers. You can only inject providers to config.

hansmaad
  • 18,417
  • 9
  • 53
  • 94
0

My opinion is that, most of the time, you shouldn't be writing code that accesses $templateCache directly at all. What you should be doing is using a build system such as gulp and a plugin such as gulp-angular-templatecache.

Then your templates are simply a bunch of .html files, your editor recognises them as html and does the appropriate linting while you edit, and all you have to do is ensure your app declares a dependency on the template module.

So the code you gave above would become:

var myApp = angular.module('myApp', ['myappTemplates']);

and the use of $templateCache inside .run() is pushed down to automatically generated code that you never see.

Duncan
  • 92,073
  • 11
  • 122
  • 156