-2

in Angularjs's developer guide a controller created in below schema:

.controller('MyController', ['$scope', function($scope) {
  $scope.username = 'World';
}]);

but i see in some other places they use another way to create their controllers like below:

.controller('MyController', function($scope) {
  $scope.username = 'World';
});

What is Differences when we use brackets in controller definition or not?

bobsilon
  • 1,648
  • 4
  • 20
  • 33
  • Imagine what will happen with the 2nd example when you minify. – Neil Smith Dec 18 '14 at 16:42
  • 1
    See https://docs.angularjs.org/tutorial/step_05#a-note-on-minification – Rhumborl Dec 18 '14 at 16:43
  • I think, the first one is a little bit faster as all the dependencies in the list as far as I know the other method parses function.toString() (no sure if here a method to get parameters directly) – Onur Topal Dec 18 '14 at 16:48

1 Answers1

2

It allows for code minification. With Angular's dependency injection, the names of the variables (as the function parameters) being injected matter, and a code minifier could change them. If you provide the string versions of the variable names (in order), Angular will be able to inject the correct dependency even if the minifier changed the variable name.

If you had the original code:

.controller('MyController', function ($http) {

Then Angular's DI knows to inject the $http service. But If you run this through a code minifier, it could change your code to this:

.controller('MyController', function (a) {

Now Angular doesn't know what a is, because it relies on the name of the variable to find the correct dependency. If you supply a string version of the dependency name, then Angular will be able to resolve it correctly even though $http was changed to a:

.controller('MyController', ['$http', function (a) {
Mike
  • 4,071
  • 21
  • 36