角公约,宣布控制器公约、控制器

2023-09-13 04:43:57 作者:若即若離

有没有对控制器的声明中建立规则? (或任何形式的模块级的配置)。

Is there an established convention regarding declaration of controllers? (Or any form of module-level configuration).

我已经观察到使用两种不同的方法:

I have observed two different approaches in use:

var shoppingCartModule = angular.module('ShoppingCart',[])
shoppingCartModule.controller('CheckoutCtrl', function($scope) { ... });

VS

angular.module('ShoppingCart').controller('CheckoutCtrl', function($scope) { ... });

是否有两种方法之间什么好处?此外,有没有一个preferred(或新兴的)约定?

Are there any benefits between the two approaches? Also, is there a preferred (or emerging) convention?

我在不平凡的应用程序有很多模块,其中控制器和模块的声明可能跨越多个文件的好处特别感兴趣。

I'm specifically interested in benefits for non-trivial apps with many modules, where declarations of controllers and modules may span many files.

推荐答案

我个人做以下(原因后):

Personally I do the following (reasons after):

angular.module('myApp', []);

angular.module('myApp').controller('myController', ['$dependency', 'anotherDependency',      
  function($dependency, anotherDependency) {
    ...
  }
]);

原因:

我尽量避免全局范围内用绳子现金等价物将冗余声明依赖性允许您安全地运行如下的code 这是一致的,干净,整个故事是存在的。例如。与 app.something 你不知道什么是应用是,使用`angular.module('对myApp')。东西'这是pretty明显那是什么。 I try and avoid the global scope Redundantly declaring dependencies with string equivalents allows you to safely minify your code It's consistent, clean and the whole story is there. Eg. with app.something you don't know what app is, with `angular.module('myApp').something' it's pretty obvious what that is.

的 修改的:只记得一个很酷的视频前一阵子我对这个题目看到 - 的 http://www.egghead.io/video/tTihyXaz4Bo 。如果你还没有签出约翰的网站,我强烈推荐它。我是他的影片我捐pssed这样的IM $ P $,而你也应该这么做!

Edit: Just remembered a cool video I saw on this very topic a while ago - http://www.egghead.io/video/tTihyXaz4Bo. If you haven't checked out John's site, I highly recommend it. I was so impressed with his videos I donated, and you should too!