简体   繁体   English

AngularJS多次定义angular.module()

[英]AngularJS defining angular.module() multiple times

What is the behaviour of calling angular.module('myModule') multiple times? 多次调用angular.module('myModule')的行为是什么?

For example, I wish to define my routes and my directives in separate .js files. 例如,我希望在单独的.js文件中定义我的路由和我的指令。

Is this safe? 这样安全吗?

eg: 例如:

//routes.js
angular.module('app',['$strap'])
   .config(function($routeProvider, $locationProvider) {
     ...
   });

//directives.js
angular.module('app')
    .directive('formInput', function() {
...

Also, what is the impact of defining the dependencies multiple times? 此外,多次定义依赖项的影响是什么? Is this additive, or last-in-wins? 这是添加剂还是最后一次胜利?

eg: 例如:

angular.module(name[, requires], configFn); angular.module(name [,requires],configFn);
... ...
requires(optional) – {Array.=} – If specified then new module is being created. requires(可选) - {Array。=} - 如果指定,则创建新模块。 If unspecified then the the module is being retrieved for further configuration. 如果未指定,则检索模块以进行进一步配置。 -- angular.module docs - angular.module docs

I would interpret that as follows: you can only define the dependencies once -- the first time you call angular.module for a particular module. 我会解释如下:您只能定义一次依赖项 - 第一次为特定模块调用angular.module。 You can call angular.module() multiple times after that, but the requires option must not be specified. 之后可以多次调用angular.module(),但不能指定requires选项。

You should only create your module once. 您应该只创建一次模块。 According to the docs , if you create a module with a name that already exists, it will overwrite the previous one. 根据文档 ,如果您创建一个名称已存在的模块,它将覆盖前一个模块。 (So last-in-wins.) (所以最后胜利。)

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

You can retrieve your module as many times as you like and in separate files if you wish. 您可以根据需要多次检索模块,也可以根据需要在单独的文件中检索模块。 You will typically retrieve your module multiple times to declare services, controllers, directives, etc. 您通常会多次检索模块以声明服务,控制器,指令等。

angular.module('app').service('myService', ...);
angular.module('app').controller('myController', ...);
angular.module('app').directive('myDirective', ...);

In the AngularJS docs on Modules , see the section called Creation versus Retrieval . 关于模块AngularJS文档中 ,请参阅“ 创建与检索 ”一节。

I'm new to angular, but this is my understanding: you create one module in each file with a namespaced module name, and in your main module you require those modules. 我是angular的新手,但这是我的理解:你在每个文件中创建一个带有命名空间模块名称的模块,在主模块中你需要这些模块。

// in main app.js file
var app = angular.module('myapp', 
          ['myapp.routers', 'myapp.directives', 'myapp.filters']);

// in filters.js
angular.module('myapp.filters', []).filter(....)

// in routers.js
angular.module('myapp.routers', []).router(....)

// in directives.js
angular.module('myapp.directives', []).directive(....)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM