angular.injector vs $injector

48 views
Skip to first unread message

Ku buś

unread,
May 23, 2016, 6:15:51 PM5/23/16
to AngularJS
Iam having a problem where I want to use angular.injector(["ng"]) in my controller. The problem is that whenever I compare injectors the compare is false, why is that?

Also in the example you can see the cached result is undefined.


http://plnkr.co/edit/ll8y3ce2521v0dzRNKeF?p=preview

Sander Elias

unread,
May 24, 2016, 1:40:37 AM5/24/16
to AngularJS
Hi Ku,

I updated your sample to work:

angular
 
.module('app', []);
 
.run(function($templateCache, $injector) {
   
var compare = angular.injector(["ng"]) === $injector
   
//alert(compare); // false is the correct answer in this case. you created an new injector that's not linked to the module.


   $templateCache
.put("something.html","You some actual content here!");
   
var cached = $templateCache.get("something.html");
    alert
(cached);
 
});

When you find the need to use the injector yourself, you have probably a code-smell. This is not something you should need in a normal app. 
May I ask what use case you needed the injector for in the first place?

Regards
Sander

Ku buś

unread,
May 24, 2016, 3:26:13 AM5/24/16
to AngularJS
In my application I have like 10 directives that have own html template. In application run I would like to put all templates in cache and in directives method "template" I would like to retrieve correct template. I know I can do this by injecting $templateCache to each directive. But its really annoying that I have to do this for each directive. I come up with idea that I already have baseDirective for all directives and I just need a $templateCache instance without dependency injection.

Regards,
Qba

Sander Elias

unread,
May 24, 2016, 10:20:15 AM5/24/16
to AngularJS
Hi Ku,

I think you are better off with a build step for that. I use gulp-angular-templatecache just for that. It gobbles up all my template files, and spits out an module you can include that stuffs all of it in the $templateCache

Regards
Sander
Reply all
Reply to author
Forward
0 new messages