Mar*_*sos 15 javascript angularjs angularjs-module
在AngularJS中处理大型项目时,我发现我喜欢按功能组织代码.
这意味着当我有一些可识别的功能X(特别是如果它是可重用的)时,我创建目录X并将所有控制器,服务和属于该功能的其他部分放入其中.我还声明了一个名为X的新模块,并将目录X中的所有内容分配给该模块.
目录结构看起来像这样:
scripts/
app.js
controllers/
services/
directives/
filters/
X/
controllers/
services/
directives/
filters/
Run Code Online (Sandbox Code Playgroud)
在app.js中有一个主模块声明:
angular.module('myApp', ['X']);
Run Code Online (Sandbox Code Playgroud)
X /中的所有控制器等都属于模块'X',这意味着我在这些文件中获取模块'X':
var X = angular.module('X');
Run Code Online (Sandbox Code Playgroud)
我不知道怎么做是在哪里声明模块'X'?
我有一些想法:
angular.module('myApp', ['X']);
angular.module('X', [/*some dependencies could go here*/]);有没有更好的方法来做到这一点?
dma*_*tro 15
是.第三种选择是最佳解决方案.第一种选择肯定会给颈部带来痛苦.第二个选项在主应用程序中添加模块X的依赖项,这是不可取的.您希望您的模块是自包含的.所以第三种选择是最好的解决方案.
以下是Google实际尝试遵循的最佳实践建议.:)此外,对于您(如Google的最佳实践所建议的),不要通过工件分隔文件也很好,这意味着您不需要控制器,指令等dir结构,如下所示.还要注意部分,CSS甚至组件中的测试都包含在组件/模块目录中.因此,该模块完全包含且独立,这有助于可重用性:
sampleapp/
app.css
app.js
app-controller.js
app-controller_test.js
components/
bar/ "bar" describes what the service does
bar.js
bar-service.js
bar-service_test.js
bar-partial.html
foo/ "foo" describes what the directive does
foo.js
foo-directive.js
foo-directive_test.js
foo-partial.html
index.html
Run Code Online (Sandbox Code Playgroud)
我希望这会有所帮助.