什么是依赖注入的注解与AngularJS最好的做法? [英] What is the best practice for dependency injection annotation with AngularJS?

查看:129
本文介绍了什么是依赖注入的注解与AngularJS最好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,感谢NG-注释,现在我们可以再缩小我们的code成功时,它看起来是这样的:

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?

推荐答案

这要看你的项目。如果您使用的是ngAnnotate为您的项目 - 它适用于所有的DI的情况下 - 使用它。只是要确保所有开发者遵守这个约定。注意,ngAnnotate或类似的工具是用于缩小的一个要求。

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.

在一般情况下,使用内联注释似乎是preferred,因为它像ngAnnotate构建工具没有依赖性。但是,没有理由使用ngAnnotate不应该工作。

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.

有第三种选择,以及

MyCtrl = function($scope) {
  $scope.awecomeThings = [...];  
} 
MyCtrl.$inject = ['$scope'];

angular.module('YourApp').controller('MyCTrl', MyCtrl);

这看起来如果使用的打字稿真的很好(也许CoffeeScript的吗?)

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);

这篇关于什么是依赖注入的注解与AngularJS最好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆