I understand that your question refers to the difference between the version without declaration of dependency injections...
var controller1 = function ($scope,$http){}
and the version with addition to the injectables via method controller
and with declaration of dependencies:
$myApp.controller('controller2',[ '$scope', '$http', function($scope, $http) {}]);
If that’s the case, let’s split:
No declaration of dependency injections
Your code is doing the following:
var // Declaração de variável no escopo atual
controller1 = // Nome do controller
function ( // A interface da função definirá as dependências
$scope, // Injeta a dependência para o módulo $scope
// usando o handler default
$http // Injeta a dependência para o módulo $http
// usando o handler default
){
... // Corpo da função
}
This format keeps the code lean and Terso. Dependencies are solved using your handlers standard, which is convenient if you are using a standard service repeatedly.
How Angular has no idea what controller1
means, it will map the DOM to find an object with the same name, make sure that the object is a function, and that this function can be mapped as a controller. It takes time - not much, but it’s a overhead.
With declaration of dependencies
$myApp // Referência ao objeto que contém a aplicação
.controller( // Declaração de controle
'controller2', // Nome do controller
[ // coleção de objetos; N referências a dependências,
// Último parâmetro será a função que as consome.
'$scope', // Mapeando a dependência $scope para a posição 0
'$http', // Mapeando a dependência $http para a posição 1
function( // Interface da função
$scope, // apelido (handler) da dependência na posição 0
$http // apelido (handler) da dependência na posição 1
) {
... // Corpo da função
}]);
This method is more complex, but offers more possibilities. Imagine you want to write a generic controller that expects to receive a dependency that has Get(id), Getall(), Remove methods().
Instead of rewriting your controller each time you need to implement a controller for each new implementation of this dependency, you only need to exchange the mapped reference. Example:
Original
$myApp.controller('dep1Controller',[ '$scope', 'dep1svc', function($scope, dependencia) {}]);
New version
$myApp.controller('dep2Controller',[ '$scope', 'dep2svc', function($scope, dependencia) {}]);
Internal controller functions will reference dependencia
, completely ignorant if the called methods belong to dep1svc
or dep2svc
- thus allowing a greater abstraction of its code.
I was able to understand how it worked after a while, but thank you very much for the most detailed explanation that will possibly help more people.
– claudsan