Nikolai Jakov
Nikolai Jakov

Reputation: 11

Angular $injector vs angular dependency injection

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!

Upvotes: 1

Views: 480

Answers (2)

Harris
Harris

Reputation: 1785

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

Upvotes: 0

Mistalis
Mistalis

Reputation: 18279

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) {
    // ...
}

Upvotes: 2

Related Questions