Difference between scope statement

4

Is there any difference in this scope statement mentioned in the angular documentation:

myApp.controller('DoubleController', ['$scope', function($scope) {
  $scope.double = function(value) { return value * 2; };
}]);

for this scope?

myApp.controller('DoubleController', function($scope) {
  $scope.double = function(value) { return value * 2; };
});

Apparently, both work equally well

    
asked by anonymous 21.05.2015 / 15:20

1 answer

4

Yes, there are differences.

The second uses the default nickname of the service $scope , which is the same name.

The first creates an injection of the $scope service, and uses the nickname '$ scope' to reference this service.

This implementation allows 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 implementation of the controller is the same, and the call to the function funcao() also - but the services are different.

This model is widely used when you want to deploy 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; 
        }\);
    
21.05.2015 / 15:29