如果AngularJS模块不存在,请创建它

时间:2014-03-13 10:25:40

标签: javascript angularjs

我有几个指令和工厂分布在几个文件中,但我希望它们都包含在同一个模块中。例如:

用户-account.js

var userModule = angular.module("user", []); //I create the module here
userModule.directive("userPicture", ...);

用户-transactions.js

var userModule = angular.module("user"); //I use the module here
userModule.directive("userPayment", ...);

我遇到的问题是,我需要按正确的顺序包含文件,否则它不会起作用,因为模块的创建只在user-account.js中完成。我不喜欢这样,因为这些模块的用户需要知道它的正常工作顺序。

所以我的问题是,如何以优雅的方式构建模块创建+用法?我正在考虑创建某种Singelton助手来创建模块,如果它不存在但我不喜欢这个想法。还有其他想法吗?

3 个答案:

答案 0 :(得分:2)

不要将user模块和user-account混合在同一个文件中。

<强> app.js

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

<强> user.js的

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

用户-account.js

angular.module("user").directive("userPicture", ...);

用户-transactions.js

angular.module("user").directive("userPayment", ...);

然后在 index.html

<!-- modules -->
<script src="js/app.js"></script>
<script src="js/user.js"></script>

<!-- directives -->
<script src="js/directives/user-account.js"></script>
<script src="js/directives/user-transactions.js"></script>

答案 1 :(得分:0)

我建议在这种情况下使用requirejs。然后,您不必担心脚本文件的排序。

答案 2 :(得分:0)

我遵循书中Mastering Web Application Development with Angularjs的风格,链接是书中解释的整个例子。

这种风格的主要思想是 1.通过businsess功能而不是按类型划分的潜水代码; 2.将一个模块中的所有内容放入一个文件中,例如:

// myApp.js

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

// user.js的

angular.module('user', [])
.directive("userPicture", ...);
.directive("userPayment", ...);

// index.html的:

<script src="js/app.js"></script>
<script src="js/user.js"></script>

为什么这样做无论是指令,服务还是控制器,他们都在相互交谈,在一个文件中你不需要切换文件。

是的,你可能会夸大模型文件,但分离到另一个模型是个好兆头。

我在我的项目中使用该样式,并且我发现代码比以前更具可读性。