简体   繁体   中英

AngularJS defining angular.module() multiple times

What is the behaviour of calling angular.module('myModule') multiple times?

For example, I wish to define my routes and my directives in separate .js files.

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);
...
requires(optional) – {Array.=} – If specified then new module is being created. If unspecified then the the module is being retrieved for further configuration. -- 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. You can call angular.module() multiple times after that, but the requires option must not be specified.

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 .

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.

// 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(....)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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