声明模块的“最佳”方法
由于angular本身在全局范围内,并且模块已保存到其变量中,因此您可以通过
angular.module('mymod')以下方式访问模块:// one file// NOTE: the immediately invoked function expression // is used to exemplify different files and is not required(function(){ // declaring the module in one file / anonymous function // (only pass a second parameter THIS ONE TIME as a redecleration creates bugs // which are very hard to dedect) angular.module('mymod', []);})();// another file and/or another anonymous function(function(){ // using the function form of use-strict... "use strict"; // accessing the module in another. // this can be done by calling angular.module without the []-brackets angular.module('mymod') .controller('myctrl', ['dep1', function(dep1){ //.. }]) // appending another service/controller/filter etc to the same module-call inside the same file .service('myservice', ['dep2', function(dep2){ //... }]); // you can of course use angular.module('mymod') here as well angular.module('mymod').controller('anothermyctrl', ['dep1', function(dep1){ //.. }])})();不需要其他全局变量。
当然,这完全取决于偏好,但是我认为这是最好的做法,因为
- 您不必污染全球范围
- 您可以随处访问模块并将其及其功能随意分类到不同的文件中
- 您可以使用“使用严格”功能形式;
- 文件的加载顺序无关紧要
用于对模块和文件进行排序的选项
这种声明和访问模块的方式使您非常灵活。您可以通过函数类型(如另一个答案中所述)或通过路由对模块进行排序,例如:
angular.module('home')...angular.module('another-route')...angular.module('shared')...最终如何排序取决于个人喜好以及项目的规模和类型。我个人喜欢将模块的所有文件归入同一文件夹(按指令,控制器,服务和过滤器的子文件夹排序)中的所有文件,包括所有不同的测试文件,因为它使您的模块更可重用。因此,在中型项目中,我最终得到一个基本模块,该模块包括所有基本路径及其控制器,服务,指令和或多或少复杂的子模块,当我认为它们也可能对其他项目有用时,例如:
/controllers/directives/filters/services/my-map-sub-module/my-map-sub-module/controllers/my-map-sub-module/servicesapp.js...angular.module('app', [ 'app.directives', 'app.filters', 'app.controllers', 'app.services', 'myMapSubModule']);angular.module('myMapSubModule',[ 'myMapSubModule.controllers', 'myMapSubModule.services', // only if they are specific to the module 'myMapSubModule.directives', 'myMapSubModule.filters']);对于非常大的项目,有时我会如上所述按路线或按某些选定的主要路线甚至是路线与某些选定组件的组合对模块进行分组,但这确实取决于实际情况。
编辑: 只是因为它是相关的,并且我最近又遇到了这个问题: 请注意,您只能创建一个模块一次 (通过向angular.module-
function添加第二个参数)。这会使您的应用程序混乱,并且很难检测。
2015年对排序模块的编辑:
一年半的经验之后,我可以补充一点,因为在AMD中仍然不能很好地与Angular以及服务,指令和过滤器配合使用,因此在您的应用程序中使用命名不同的模块所带来的收益有限无论如何都可以在角度上下文中全局使用。但是,仍然存在语义和结构上的好处,并且能够包含/排除带有注释掉或注释掉一行代码的模块可能会有所帮助。
由于 子模块 通常彼此依赖,因此 按类型分隔子模块 (例如,“ myMapSubModule.controllers”)几乎也没有多大意义 。



