What is the difference between these two angularjs controller definition

126 Views Asked by At

I don't understand the difference between these two types of angularjs controller definition, i have tried following codes and found both working

myApp.controller('GreetingController', ['$scope', function($scope) {
  $scope.greeting = 'Hola!';
}]);

myApp.controller('GreetingController', function($scope) {
  $scope.greeting = 'Hola!';
});
2

There are 2 best solutions below

2
On BEST ANSWER

First one cares about minification.

In this controller:

myApp.controller('GreetingController', function($scope) {
    $scope.greeting = 'Hola!';
});

arguments will be minimized to some short values and dependency injection will not work.

Please look at:

0
On

The second one won't work anymore once minified, because the minifier will rename the parameters to spare as much bandwidth as possible:

myApp.controller('GreetingController', function(a) {
    a.greeting = 'Hola!';
});

Since angular uses the names of the arguments to know what to inject to the controller, that will fail.

The first syntax is a way to circumvent this problem.

I use ngAnnotate in order to automatically transform the second syntax to the first one, as part of the build process, before minifying