Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

like image 537
Marty Pitt Avatar asked Jan 17 '13 02:01

Marty Pitt


People also ask

Can we have multiple modules in AngularJS?

Yes, you can define multiple modules in angularJS as given below. The modularization in AngularJS helps us to keep the code clarity and easy to understand, as we can combine multiple modules to generate the application.

How define module in AngularJS?

An AngularJS module defines an application. The module is a container for the different parts of an application. The module is a container for the application controllers. Controllers always belong to a module.

What is $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods.

Can we have multiple controllers in AngularJS?

An AngularJS application can contain one or more controllers as needed, in real application a good approach is to create a new controller for every significant view within the application.


2 Answers

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.

like image 70
Mark Rajcok Avatar answered Oct 14 '22 17:10

Mark Rajcok


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.

like image 42
James Lawruk Avatar answered Oct 14 '22 16:10

James Lawruk