What is the difference between these two angularjs controller definition

100 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 answers

2
kTT 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
JB Nizet 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