Where should I use $templateCache?

317 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

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.