Difference between Cope declaration

Asked

Viewed 351 times

4

Is there any difference in that Cope statement 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, both work equally in the same way

1 answer

4


Yes, there are differences.

The second uses the standard service nickname $scope, homonymous.

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

This implementation allows for greater flexibility - imagine a generic controller, which you can invoke by passing different services as reference:

myApp.controller('DoubleController', ['servicoTipo1', function(servico) {
  servico.funcao();
}]);

myApp.controller('DoubleController', ['servicoTipo2', function(servico) {
  servico.funcao();
}]);

Controller implementation is the same, and function call funcao() also - but the services are different.

This template is often used when you want to implement controllers reusable:

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; 
        }\);
  • 2

    Question: Is this useful also in case of minifying the file? If the second example posted by AP was minified, it would probably have the parameter $scope exchanged for one a (or some similar name) that Angularjs would ignore. Or what I said has nothing to do with?

  • @Renan Sounds like a good idea. I don’t see why a good one postprocessing parser I would not carry out this minification, but I confess that I ignore the existence of any who do it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.