了解 Angularjs 中的编码风格 [英] Understanding coding style in Angularjs

查看:23
本文介绍了了解 Angularjs 中的编码风格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Angularjs 时遇到了不同的编码风格,这让我思考了每种编码风格的优缺点.

I came across different coding style using Angularjs and it made me think what the advantage and disadvantage of each coding style.

例如.控制器声明:

样式 #1

angular.module('mainCtrl', []);
function MainCrl($scope, $rootScope) {}

风格#2

angular.module('mainCtrl',[])
.controller('MainCtrl', function($scope, $rootScope)) { ... });

样式 #3

angular.module('mainCtrl',[])
.controller('MainCtrl', ['$scope', '$rootScope', function(scope, rootScope)) { ... }]);

因此样式 #3 有点像使用别名,当您要编写测试脚本(单元测试)时,使用别名是否有影响?.我只是想在使用 Angularjs 框架时有更好的理解和正确的方法.

Hence style #3 is somewhat like using an alias, does using an alias have an effect when your going to write a testscript (unit testing)?. I just want to have a better understanding and the correct approach when using Angularjs Framework.

请分享您对此的看法.谢谢!

Please do share your thoughts about this. Thanks!

推荐答案

Style #1 意味着控制器在模块外部定义为全局变量,对于小型测试项目没问题,但对于任何严肃的工作,一切都应该使用 #2 来完成或#3.#2 和 #3 之间的区别在于 #3 是可以缩小的,因为 #2 中的 $scope 和 $rootScope 名称通常会被优化掉,这会导致应用程序失败.#3 将这些存储为不会被缩小的字符串.

Style #1 means the controllers are defined outside of the module as globals, alright for small test projects but for any serious work, everything should be done using #2 or #3. The difference between #2 and #3 is #3 is minifiable as the $scope and $rootScope names in #2 will normally be optimised out, which causes the application to fail. #3 Stores these as strings which will not be minified out.

如果至少有可能缩小代码,请选择 #3.使用 #1 而不是 #2 没有什么意义,所以我倾向于完全避免 #1.

If there's at least a possibility that you'll be minifying your code, go for #3. There's very little point in using #1 over #2 so I tend to avoid #1 altogether.

这篇关于了解 Angularjs 中的编码风格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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