Why do angularjs controller declaration have this syntax structure?

The array syntax will help you with minification/uglify of your js code.

angular.module('7minWorkout').controller('WorkoutController', 
  function ($scope, $interval, $location) {
    // code here
});

Will be minified and mangled as:

angular.module('7minWorkout').controller('WorkoutController', 
 function (a, b, c) {
    // code here
});

So Angular won’t be able to figure out which dependencies to inject

On the other hand, using the array declaration:

angular.module('7minWorkout').controller('WorkoutController', 
 ['$scope', '$interval', '$location', function ($scope, $interval, $location) {
    // code here
}]);

Will be minified as :

angular.module('7minWorkout').controller('WorkoutController', 
  ['$scope', '$interval', '$location', function (a, b, c) {
    // code here
}]);

So Angular will know what a, b and c represent.


There’s also another way to inject variables if you use your first example code like below:

WorkoutController.$inject = ['$scope', '$interval', '$location'];

or

angular.module('7minWorkout').controller('WorkoutController', /* @ngInject */
  function ($scope, $interval, $location) {
   // code here
});

which will create the $inject method mentioned above when the code is annotated.


So, there are mainly four kinds of annotation:

  1. Implicit Annotation – the first example code
  2. Inline Array Annotation – the second example code
  3. $inject Property Annotation – the $inject method
  4. $ngInject Comment Annotation – the @ngInject method

ng-annotate

Tools like ng-annotate let you use implicit dependency annotations in your app and automatically add inline array annotations prior to minifying. If you decide to take this approach, you probably want to use ng-strict-di.

For more information, see AngularJS Developer Guide – Using Strict Dependency Injection.

Leave a Comment