1

I am pretty new to Angular. I see there is a thing called $injector whose function, get, I can use to get a specific service. For example:

app.factory('$myService', function($injector) {
   return { ...
            var http = $injector.get('$http');
            ....
   }
}

I will get the $http service of Angular to the variable http.

In other examples I see something like

app.factory('$myService', function($http) {
    return {...}

This also inject the $http service into the factory.

Is there a difference between the two? When should I use this or that?

Thank You!

Paul Simpson
  • 2,504
  • 16
  • 28
  • See ["What's the difference between the Dependency Injection and Service Locator patterns?"](http://stackoverflow.com/questions/1557781/whats-the-difference-between-the-dependency-injection-and-service-locator-patte) - Angular's constructor injection is an example of the former, and `$injector` is an example of the latter. You're better off using constructor injection unless you have a very good reason not to. – Joe Clay Jan 18 '17 at 16:18
  • @NikolaiJakov Can you accept an answer if your issue is solved? :) – Mistalis Jan 23 '17 at 07:53

2 Answers2

2

Is it the same, use the one you prefer.

In my opinion, injecting directly your dependencies (here it is $http) is better for readability.


Note that you can also use the $inject annotation:

someModule.controller('MyController', MyController);
MyController.$inject = ['$http'];

var MyController = function($http) {
    // ...
}
Mistalis
  • 17,793
  • 13
  • 73
  • 97
0

They're largely the same, but how you can use them differs. In a typical controller that you know the requirements for ahead of time, it's typically better to do parameter-based injection:

var controller = ['$http', function($http){ /* Controller stuff here */ }];

However, if you're doing something more complex and you don't know all of the dependencies you might have (e.g. Creating a sub-framework that allows users to specify dependencies), you may want to be able to programmatically inject your dependencies with $injector:

var controller = ['$scope','$injector', function($scope, $injector){
    $scope.dependencies = [];
    $scope.injectFromString = function(dependency){
        $scope.dependencies.push($injector.get(dependency));
    };
}];`
Harris
  • 1,775
  • 16
  • 19