AngularJs Modules.
A module in AngularJS can be thought of as regular packages in Java. It’s the container for the different parts of an application – controllers, services, filters, directives, etc. AngularJS can group together certain functionalities/Javascript under a single module.
- A module can define it’s own controllers, services, filter, directives, etc which will be accessible throughout the module.
- A module can depend on other modules.
- A module can be used by AngularJS to bootstrap an application. By passing the module name to ng-app directive, we can tell AngularJS to load this module as the main entry point for the application.
In angularJS, a module is defined or called using angular.module
function.
Define a Module with no dependencies
angular.module('myapp', []);
The first argument is the module name, ‘myApp’. The second argument is an array of module names that this module depends on. Empty square brackets denotes that this module does not have any dependencies.
Define a Module with dependencies
Below snippet defines a module named myApp, which depends on two other modules: ui.bootstrap & ngResource:
angular.module('myapp', ['ui.bootstrap', 'ngResource']);
It means all the functionalities available in ‘ui.bootstrap’ & ‘ngResource’, will be accessible throughout module ‘myApp’.
Load an existing Module
If we just want to load an existing module defined elsewhere, call module function with only one parameter which is name of module.
angular.module('myApp');
Let’s take a simple example:
<html ng-app="myApp"> <head><title>Modle example</title></head> <body> 2 + 2 = {{2 + 2}} <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"> </script> <script> angular.module('myApp', []); </script> </body> </html>
Above example defines a module. AngularJS then bootstraps the application using this module through the ng-app directive.
Till now, we have just created empty modules. There is nothing inside them. We will add functionality to them in next posts.
If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help improve further our learning process.