be-codified
be-codified

Reputation: 6144

Dependency injection in Angular JS

I already read the AngularJS documentation but still don't have an answer which I understand.

Why is this used twice? One time as array elements, the second as function parameters.

someModule.controller('MyController', ['$scope', 'greeter', function($scope, greeter) {
  // ...
}]);

Upvotes: 2

Views: 139

Answers (2)

Xxx Xxx
Xxx Xxx

Reputation: 143

Minification convert your code in something more light and fast to download. You just have to do something like a declaration of the dependency injection before putting it in the function and use it, BUT just in the case you'll need to use minification.

Your function need "$scope" and "greeter". If you write this way:

someModule.controller('MyController', function($scope, greeter) {  // ...
});

..and then use minification, the controller will turn to:

someModule.controller('MyController',function(a,b) {  // ...
});

..Then your controller "MyController" will not understand where the hell are "$scope" and "greeter", it will only see a parameter "a" and a parameter "b".

For this reason the best way is to use an array:

 someModule.controller('MyController', ['$scope', 'greeter', function($scope, greeter) {  // ...
}]);

..and then use minification:

someModule.controller('MyController', ['$scope', 'greeter', function(a, b) {  // ...
}]);

As you can see the first and second element of the array are not converted and javascript will knows that "a" and "b" are the elements inside the array to put in the function.

Notice that if you write something like:

    someModule.controller('MyController', ['$scope', '$log', function($log, $scope) { 
console.log($scope);  
    }]);

You'll have the console log of the $log! This because the position and ONLY the position matters, you could name:

    someModule.controller('MyController', ['$scope', '$log', function(Donald, Duck) { 
console.log(Duck);  
    }]);

It will send you back the console log of the $log element.

Upvotes: 1

sp00m
sp00m

Reputation: 48837

If you minify this code:

someModule.controller('MyController', function($scope, greeter) {
  // ...
});

You'll end with (something like):

someModule.controller('MyController', function(a, b) {
  // ...
});

Angular won't be able to inject the dependencies since the parameters names are lost.

On the other hand, if you minify this code:

someModule.controller('MyController', ['$scope', 'greeter', function($scope, greeter) {
  // ...
}]);

You'll end with:

someModule.controller('MyController', ['$scope', 'greeter', function(a, b) {
  // ...
}]);

The parameters names are available: Angular's DI is operational.

Upvotes: 2

Related Questions