AngularJS中的编码风格

Tib*_* F. 5 coding-style angularjs

虽然这个线程总结了以下三种代码样式:

1)

angular.module('mainCtrl', []);
function MainCrl($scope, $rootScope) {}
Run Code Online (Sandbox Code Playgroud)

2)

angular.module('mainCtrl',[])
.controller('MainCtrl', function($scope, $rootScope)) { ... });
Run Code Online (Sandbox Code Playgroud)

3)

angular.module('mainCtrl',[])
.controller('MainCtrl', ['$scope', '$rootScope', function(scope, rootScope)) { ... }]);
Run Code Online (Sandbox Code Playgroud)

在这个视频中看到的第四种方式对我很有吸引力

4)

var controllers = {}
controllers.mainCtrl = function($scope, $rootScope){ };
app.controller(controllers)
Run Code Online (Sandbox Code Playgroud)

我倾向于继续4),如果缩小它会破裂还是有任何其他缺点?我应该选择3)因为它似乎是标准的做法吗?

Gol*_*den 5

我的建议:选择3,有三个原因:

  1. (IMHO)是最广泛采用的一种.
  2. 你没有缩小的问题(这是唯一的选择,这是真的).
  3. 它最适合模块.


Ste*_*wie 5

  • 选项1污染全局命名空间并阻碍缩小并且不尊重模块.
  • 选项2不允许您在控制器签名中重命名注射器.
  • 选项4污染了全局命名空间,但如果你正确地执行它,它就是安全的1.

  • 选项3允许您重命名注射器2,尊重模块,不污染全局命名空间,并且在缩小时不需要任何额外的工作.

所以我的赢家是选项#3.


1选项4 - 缩小版本:

var controllers = {};
controllers.mainCtrl = ['$scope', '$rootScope', function($scope, $rootScope){ ... }];
app.controller(controllers);
Run Code Online (Sandbox Code Playgroud)

2重命名注射剂:

app.controller('MyCtrl', ['$scope', 'UserService', function($scope, User){ ... }]);
Run Code Online (Sandbox Code Playgroud)