ltfishie
ltfishie

Reputation: 2987

Angular controller explicit depedency injection

Reading through the various tutorial on the web, I came across a two different ways of registering a controller.

var app = angular.module('myApp', []);

//without explicit dependency injection
app.controller ("myCtrl1", function ($scope, $http) {
       //some implementation
});

//with explicit dependency injection
app.controller ("myCtrl2", ["$scope", "$http", function ($scope, $http) {
       //some implementation
}]);

Both seems to work equality with both $scope and $http object being available to use inside the function.

Can someone enlighten me as to the different between the two approach and if one is preferred over the other? If angular can figure out the right dependencies to be injected, what is the benefit of declaring it explicitly?

Upvotes: 1

Views: 882

Answers (2)

luca
luca

Reputation: 12611

the main difference is that, with explicit dependency injection, your dependencies are not found based on the arguments names but on the strings you pass. This allows you to use javascript minifiers without risk, because they would rename the arguments.

Upvotes: 1

Sean Vieira
Sean Vieira

Reputation: 160005

The issue is minification:

//without explicit dependency injection
a.controller ("myCtrl1", function (b, c) {
       // Broken because toString here returns
       // a, b - which are not dependencies that
       // Angular knows how to resolve
});

//with explicit dependency injection
a.controller ("myCtrl2", ["$scope", "$http", function (b, c) {
       // b and c are properly resolved
}]);

Upvotes: 3

Related Questions