我需要为 AngularJS 编写一个自定义模块,但我找不到关于该主题的任何好的文档。如何为 AngularJS 编写一个可以与其他人共享的自定义模块?
请您参考如下方法:
在这些情况下,如果您认为文档无法再帮助您,一个很好的学习方法是查看其他已经构建的模块,看看其他人是如何做到的,他们如何设计架构以及他们如何将它们集成到他们的应用程序中。
看了别人的做法,你至少应该有一个起点。
例如,查看任何 angular ui module你会看到许多自定义模块。
有些定义just a single directive ,而其他人定义 more stuff 。
喜欢@nXqd也就是说,创建模块的基本方式是:
// 1. define the module and the other module dependencies (if any)
angular.module('myModuleName', ['dependency1', 'dependency2'])
// 2. set a constant
.constant('MODULE_VERSION', '0.0.3')
// 3. maybe set some defaults
.value('defaults', {
foo: 'bar'
})
// 4. define a module component
.factory('factoryName', function() {/* stuff here */})
// 5. define another module component
.directive('directiveName', function() {/* stuff here */})
;// and so on
定义模块后,向其中添加组件非常容易(无需将模块存储在变量中):
// add a new component to your module
angular.module('myModuleName').controller('controllerName', function() {
/* more stuff here */
});
集成部分相当简单:只需将其添加为应用程序模块的依赖项(here's Angular ui 是如何做到的)。
angular.module('myApp', ['myModuleName']);