AngularJS Modules

A module in AngularJS is a container of the different parts of an application such as controller, service, filters, directives, factories etc. It supports separation of concern using modules.

AngularJS stops polluting global scope by containing AngularJS specific functions in a module.

Application Module

An AngularJS application must create a top level application module. This application module can contain other modules, controllers, filters, etc.

Example: Create Application Module
<!DOCTYPE html>
<html >
<head>
    <script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
    @* HTML content *@
    <script>
        var myApp = angular.module('myApp', []); 

    </script>
</body>
</html>

In the above example, the angular.module() method creates an application module, where the first parameter is a module name which is same as specified by ng-app directive.The second parameter is an array of other dependent modules []. In the above example we are passing an empty array because there is no dependency.

Note: The angular.module() method returns specified module object if no dependency is specified. Therefore, specify an empty array even if the current module is not dependent on other module.

Now, you can add other modules in the myApp module.

The following example demonstrates creating controller module in myApp module.

Example:Create Controller Module
<!DOCTYPE html>
<html >
<head>
    <script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
    <div ng-controller="myController">
        {{message}}
    </div>
    <script>
        var myApp = angular.module("myApp", []); 

        myApp.controller("myController", function ($scope) {
            $scope.message = "Hello Angular World!";
        });
    </script>
</body>
</html>

In the above example, we have created a controller named "myController" using myApp.controller() method. Here, myApp is an object of a module, and controller() method creates a controller inside "myApp" module. So, "myController" will not become a global function.

Modules in Separate Files

In the controller example shown above, we created application module and controller in the same HTML file. However, we can create separate JavaScript files for each module as shown below.

Example:Angular Modules in Separate Files
<!DOCTYPE html>
<html >
<head>
    <script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
    <div ng-controller="myController">
        {{message}}
    </div>
<script src="app.js" ></script>
<script src="myController.js" ></script>
</body>
</html>
app.js
var myApp = angular.module("myApp", []);
myController.js

myApp.controller("myController", function ($scope) {
    $scope.message = "Hello Angular World!";
});

Visit AngularJS documentation for more information of Module.