Modules

Think of AngularJS modules as containers, which allow you to logically group objects like i.e. controllers in your AngularJS application. This alows you to reuse modules if needed. Additionally modules act also like namespaces for your objects. See the diagram below to understand how modules fit into an AngularJS application:

AngularJS Basic Application Architecture

Do you remember the controller from the controller-tutorial? Let’s see how we can use it in a module!

Example

<!DOCTYPE html>
<html ng-app="myApp">
<body>
	<div ng-controller="ProductController">
		Category: <input type="text" ng-model="product.productCategory">&nbsp;
		Product: <input type="text" ng-model="product.productName">

		<p>Function-Output: {{ product.getDisplayName() }} </p>
	</div>   

	<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> 

	<script type="text/javascript">
		// Declare a module
		var myApp = angular.module('myApp', ['productModule']);
		var productModule = angular.module('productModule', []);

		// Add controller to module
		productModule.controller('ProductController', ['$scope', function($scope) {
			$scope.product = {
				productName: "Dell XT200",
				productCategory: "Computer",
				getDisplayName: function() {
					var p = $scope.product;
					return p.productCategory + " - " + p.productName;
				}
			};
		}]);
    </script>
</body>
</html>

Play with example »

As you can see the first part of the html-body is almost the same, except that we added the root-module myApp to the ng-app directive. This tells AngularJS to auto-bootstrap the myApp-module and its dependencies.

The next let’s examine the script-part. First you can see the creation of the root-module myApp and the productModule. To do this, AngularJS provides the method angular.module, which has the following definition:

angular.module('<ModuleName>', ['<DependentModule1>', '<DependentModule2>']);

To add our ProductController, we need to register it to module. Let’s look at the function-definition first:

moduleVariable.controller('<ControllerName>', ['$scope', <ControllerObject>]);

In our case we name it ‘ProductController and pass the object we defined in the controller-tutorial to the method.