如何为 AngularJS 编写自定义模块? [英] How do I write a custom module for AngularJS?

查看:37
本文介绍了如何为 AngularJS 编写自定义模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为 AngularJS 编写一个自定义模块,但我找不到关于该主题的任何好的文档.如何为 AngularJS 编写可与他人共享的自定义模块?

I need to write a custom module for AngularJS, but I can't find any good documentation on the subject. How do I write a custom module for AngularJS that I can share with others?

推荐答案

在这些情况下,您是否认为文档无法再帮助您,一个很好的学习方法是查看其他已经构建的模块和看看其他人是如何做到的,他们如何设计架构以及他们如何将它们集成到他们的应用中.
看了别人的做法后,你至少应该有一个起点.

In these situations were you think that the docs can't help you any more, a very good way to learn is to look at other already-build modules and see how others did it, how they designed the architecture and how they integrated them in their app.
After looking at what others did, you should have at least a starting point.

例如,看看任何 angular ui 模块,你会看到许多自定义模块.
有些定义只是一个指令,而其他人定义了更多内容.

For example, take a look at any angular ui module and you will see many custom modules.
Some define just a single directive, while others define more stuff.

@nXqd所说,创建模块的基本方式是:

Like @nXqd said, the basic way to create a module is:

// 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

定义模块后,向其中添加组件非常容易(无需将模块存储在变量中):

After defining your module, it's very easy to add components to it (without having to store your module in a variable) :

// add a new component to your module 
angular.module('myModuleName').controller('controllerName', function() {
    /* more stuff here */
});

集成部分相当简单:只需将其添加为应用模块的依赖项(这里是 angular ui 是如何做到的.

And the integration part is fairly simple: just add it as a dependency on your app module (here's how angular ui does it).

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

这篇关于如何为 AngularJS 编写自定义模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆