Both of these work, but what is the actual difference between each implementation? I'm sure there is a logical reasoning behind each method, and I wish to be enlightened.
angular.module('app').controller('GeneralCtrl',
function($scope, $location, exampleService) {
$scope.variable = exampleService.getExampleVariable();
}
);
angular.module('app').controller('GeneralCtrl',
['$scope', '$location', 'exampleService', function($scope, $location, exampleService) {
$scope.variable = exampleService.getExampleVariable();
}]
);
What is the actual difference between these? Where would you use them differently? Why?
Answer: Turns out the latter is minification safe as minifiers rename parameter names, so dependencies cannot be inferred from their names, and so must be annotated.
This is what Angular calls "inline notation" for dependency injection (see http://docs.angularjs.org/guide/di for a whole lot of detail).
In the example you gave, the ng-controller
directive is actually doing the work behind the scenes, of hooking up $scope
, $location
, and exampleService
into the variables you're providing to that first function
. It's doing this by default based on variable names (that is, it assumes that a variable called $scope
is asking for the $scope
dependency).
That said, when you minify your code, the variable names get chopped down also (ie, $scope
might become a
). When that happens, Angular now doesn't know what you meant by the variables anymore.
One option is to add
GeneralCtl.$inject('$scope', '$location', 'exampleService')
Another is to provide those strings like you did in the second example. This makes sure that even if the variable names get changed around, you're telling Angular what they were supposed to represent, and it knows how to set them properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With