javascriptangularjsangularjs-injector

When to use $injector in AngularJS


As I'm parsing through AngularJS documentation, I thought I would post this to get some other opinions.

My specific scenario is that I have settings I wish to change on an injectable using the run method of my module. I have a couple of different ways I can access the injectable and wasn't sure if there was a discernible functional advantage to using one over the other. Or do they boil down to essentially the same thing.

Say for instance my module is defined as thus:

var app = angular.module('MyModule', ['some.Third.Party.Module']);

Now consider that there is a factory in the third party module with variable that needs to be set. This can be accomplished by doing the following:

app.run(['some.Third.Party.Module.Factory', function (theFactory) {
    theFactory.someVariable = 'foo';
}]);

An alternative method would be:

app.run(function ($injector) {
    var theFactory = $injector.get('some.Third.Party.Module.Factory');
    theFactory.someVariable = 'foo';
});

Is one method better than the other? Maybe there is a third option I haven't considered yet?


Solution

  • You are actually using the three different methods (to my knowledge) Angular provides for injecting dependencies.

    Angular can identify a dependency solely through the name of a function parameter. You are doing this here when you inject $injector.

    app.run(function ($injector) { ... });
    

    The above is quick and easy for development but you can run into problems when minifying code as variable names can change.

    For production, and generally a good practice in development is to use annotations as you already have in your second code example for some.Third.Party.Module.Factory.

    app.run(['$injector', function ($injector) { ... }]);
    

    The third way I know of is to use $injector directly. This is useful for unit testing and if perhaps you wanted to conditionally switch up which dependency is injected. It provides dynamic annotation rather than static.