我需要为AngularJS编写一个自定义模块,但是我找不到关于这个主题的任何好的文档.如何为AngularJS编写可以与他人共享的自定义模块?
gio*_*_13 80
在这些情况下你认为文档不能再帮助你了,一个非常好的学习方法是查看其他已经构建的模块,看看其他人如何做到这一点,他们如何设计架构以及如何将它们集成到他们的应用.
在看了别人做了什么之后,你应该至少有一个起点.
例如,看看任何角度ui模块,您将看到许多自定义模块.
有些只定义了一个指令,而其他指定了更多东西.
就像@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
Run Code Online (Sandbox Code Playgroud)
定义模块后,可以非常轻松地向其中添加组件(无需将模块存储在变量中):
// add a new component to your module
angular.module('myModuleName').controller('controllerName', function() {
/* more stuff here */
});
Run Code Online (Sandbox Code Playgroud)
集成部分非常简单:只需将其添加为您的app模块的依赖项(这里是角度ui如何).
angular.module('myApp', ['myModuleName']);
Run Code Online (Sandbox Code Playgroud)
如果你想寻找一个好的例子,你应该研究用angularJS编写的当前模块.学习阅读他们的源代码.顺便说一下,这是我用来在angularJS中编写模块的结构:
var firstModule = angular.module('firstModule', [])
firstModule.directive();
firstModule.controller();
// in your app.js, include the module
Run Code Online (Sandbox Code Playgroud)
这是基本的.
| 归档时间: |
|
| 查看次数: |
30134 次 |
| 最近记录: |