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:
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.
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.
The $ in AngularJs is a built-in object.It contains application data and methods.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With