Search code examples
angularjsangularjs-injector

Using $injector vs. direct DI in angularjs?


I am not seeing the difference (or pros/cons) to directly injecting my dependencies vs. using $injector in angularjs. Why would I do one or the other? Here is a sample of the two.

angular
    .module("myApp")
    .factory("myService", [
        "$injector", function($injector) {

            var $http = $injector.get("$http");

            //used $injector to get $http, now get some data, etc.
        }
    ]);

angular
    .module("myApp")
    .factory("myService", [
        "$http", function($http) {

            //just use $http to get some data, etc.
        }
    ]);

Solution

  • In most cases, the second method is simple, readable and it just works, especially if you use a precompiler that writes the string values for you, e.g. ng-annotate:

    angular.module("myApp")
        .factory("myService", /*@ngInject*/ function($http, $locale, $window) {
        });
    

    I see no reason why you should avoid it.

    The first method, using $injector should be reserved for specific cases, e.g. when there are too many injections (and you don't want to refactor right now) or in some specific cases in tests.