Question:
Is there any difference in this scope declaration mentioned in the angular documentation:
myApp.controller('DoubleController', ['$scope', function($scope) {
$scope.double = function(value) { return value * 2; };
}]);
for that scope?
myApp.controller('DoubleController', function($scope) {
$scope.double = function(value) { return value * 2; };
});
apparently they both work equally the same
Answer:
Yes, there are differences.
The second uses the default service alias $scope
, which is eponymous.
The first creates an injection of the $scope
service, and uses the alias '$scope' to refer to this service.
This implementation allows for more flexibility – imagine a generic controller, which you can invoke by passing different services as a reference:
myApp.controller('DoubleController', ['servicoTipo1', function(servico) {
servico.funcao();
}]);
myApp.controller('DoubleController', ['servicoTipo2', function(servico) {
servico.funcao();
}]);
The controller implementation is the same, and the funcao()
call is the same – but the services are different.
This template is often used when you want to implement reusable controllers :
myApp.controller('controleBase', function(servico) {
servico.funcao();
});
myApp.controller(
'controleDerivado1', [
'$scope',
'$controller',
'servico1',
function ($scope, $controller, servico) {
$controller('controleBase', { $scope: $scope });
//Invoca uma nova cópia de controleBase,
//utilizando servico como referencia de servico1;
}\);