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!

2
  • See "What's the difference between the Dependency Injection and Service Locator patterns?" - 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. Commented Jan 18, 2017 at 16:18
  • @NikolaiJakov Can you accept an answer if your issue is solved? :) Commented Jan 23, 2017 at 7:53

2 Answers 2

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) {
    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

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));
    };
}];`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.