angularjsdependency-injectionng-annotate

What is the best practice for dependency injection annotation with AngularJS?


So thanks to ng-annotate, now we can minify our code successfully when it looks like this:

angular.module('YeomanApp')
  .controller('YeoCtrl', function ($scope) {
   $scope.awesomeThings = [
     'HTML5 Boilerplate',
     'AngularJS',
     'Karma'
    ];
   });

Are there any advantages to this form over this form:

angular.module('YeomanApp')
  .controller('YeoCtrl', ['$scope', function ($scope) {
   $scope.awesomeThings = [
     'HTML5 Boilerplate',
     'AngularJS',
     'Karma'
    ];
   }]);

The latter explicit dependency declaration seems to be the norm, but are there any advantages or reasons to continue using it at this point?


Solution

  • It depends on your project. If you are using the ngAnnotate for your project -- and it works for all your DI cases -- use it. Just be sure that all your devs follow this convention. Be aware that ngAnnotate or a similar tool is a requirement for minification.

    In general, using the inline annotation seems to be preferred, as it has no dependency on a build tool like ngAnnotate. But there is no reason why using ngAnnotate should not work.

    There is a third option as well

    MyCtrl = function($scope) {
      $scope.awecomeThings = [...];  
    } 
    MyCtrl.$inject = ['$scope'];
    
    angular.module('YourApp').controller('MyCTrl', MyCtrl);
    

    This looks really nice if using TypeScript (maybe CoffeeScript too?)

    class MyCtrl {
        static $inject = ['$scope'];
        contructor($scope: any) { // shouldn't use any, but this is just an example
            $scope.awesomeThings = [...];
        }
    }
    
    angular.module('YourApp').controller('MyCtrl', MyCtrl);