AngularJS模块声明的最佳实践?
我有一堆Angular模块在我的应用程序中声明。我最初开始声明他们使用“链式”语法如下:
angular.module('mymodule',[]) .controller('myctrl',['dep1',function(dep1){ ... }]) .service('myservice',['dep2',function(dep2){ ... }]) ... // more here 但我决定不是很容易阅读,所以我开始声明他们使用一个模块变量这样: var mod = angular.module('mymodule',[]); mod.controller('myctrl',function(dep1){ ... }]); mod.service('myservice',function(dep2){ ... }]); ... 第二种语法似乎对我来说更多的可读性,但我唯一的抱怨是这种语法将mod变量留在全局范围。如果我有一个名为mod的其他变量,它将被下一个(以及与全局变量相关的其他问题)覆盖。 所以我的问题是,这是最好的方法吗?或者最好做这样的事情: (function(){ var mod = angular.module('mymod',[]); mod.controller('myctrl',function(dep1){ ... }]); mod.service('myservice',function(dep2){ ... }]); ... })(); 或者甚至足够关心吗?只是想知道什么“最佳实践”是模块声明。提前致谢。
‘最好的’方式声明一个模块
由于角度在全局范围本身,模块保存到其变量,您可以通过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',function(dep1){ //.. }]) // appending another service/controller/filter etc to the same module-call inside the same file .service('myservice',function(dep2){ //... }]); // you can of course use angular.module('mymod') here as well angular.module('mymod').controller('anothermyctrl',function(dep1){ //.. }]) })(); 不需要其他全局变量。 当然,这取决于喜好,但我认为这是一种最好的做法,因为 >你不必污染全局范围 用于排序模块和文件的选项 这种声明和访问模块的方式使您非常灵活。您可以通过函数类型(如在另一个答案中描述)或通过路由对模块进行排序,例如: /******** sorting by route **********/ angular.module('home')... angular.module('another-route')... angular.module('shared')... 你最终如何排序是个人品味,项目规模和类型的问题。我个人喜欢将同一文件夹中的所有文件(命令到指令,控制器,服务和过滤器的子文件夹)分组,包括所有不同的测试文件,因为它使您的模块更可重用。因此,在中型项目中,我最终得到一个基本模块,其中包括所有基本路线及其控制器,服务,指令和或多或少的复杂子模块,当我认为它们也可以用于其他项目,例如, : /******** modularizing feature-sets **********/ /controllers /directives /filters /services /my-map-sub-module /my-map-sub-module/controllers /my-map-sub-module/services app.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' ]); 对于非常大的项目,我有时最终通过路由分组模块,如上所述或通过一些选择的主要路由,甚至路由和一些选择的组件的组合,但它真的取决于。 编辑: 2015编辑排序模块: 它也几乎从来没有什么意义,按照类型(例如’myMapSubModule.controllers’)分离子模块,因为它们通常依赖于彼此。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |