AngularJS Modules

  • by

AngularJS Modules:

  1. AngularJS Modules defines an application.
  2. It is like a container for different parts of an application – controllers, directives, filters, services, scope, etc.
  3. A controller is always defined inside a Module.
  4. Using Modules, we can create reusable blocks of code.
How to create AngularJS Module?

Module can be created by using angular.module() function.

Example:

<html>
<head>
<title>AngularJS - Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>

<script>
var app = angular.module("myApp",[]);
app.controller("myController",function($scope){
$scope.world = "Hello World";
});

</script>
</head>
<body ng-app='myApp'>
<div ng-controller='myController'>
{{world}}
</div>
</body>
</html>

VIEW DEMO

Here we are defining a module also creating a controller for it (myApp, myController). The body tag is using myApp and the div is using myController. {{world}} expression will print the message which is declared inside the controller using $scope.

OUTPUT:

angularjs-modules-example1


Defining a Controller for the Module:

All controllers must belong to a module. You can create a variable for a AngularJS module and create controller for it with two differents ways. And use the controller by using ng-controller='ControllerName' on your HTML page.

Example:

<html>
<head>
<title>AngularJS - Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>
<script>
var app = angular.module("myApp",[]).controller("controller1", function($scope){
$scope.message = "I'm from Controller 1."
});

app.controller("controller2",function($scope){
$scope.message = "I was defined in Controller 2."
});

</script>
</head>
<body ng-app='myApp'>
<p ng-controller='controller1'> {{message}}</p>
<p ng-controller='controller2'> {{message}}</p>
</body>
</html>

VIEW DEMO

OUTPUT:
angularjs-modules-controllers-usage


Modules and Controllers in a Separate file:

Most often times when creating AngularJS application, we will need to create a separate javascript file and define modules and controller inside it.

Example:
<html>
<head>
<title>AngularJS - Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script>
<script src="modules.js"></script>
</head>
<body ng-app='myApp'>
<p ng-controller='controller1'> {{message}}</p>
<p ng-controller='controller2'> {{message}}</p>
</body>
</html>

modules.js:

var app = angular.module("myApp",[]).controller("controller1", function($scope){
$scope.message = "I'm from Controller 1."
});

app.controller("controller2",function($scope){
$scope.message = "I was defined in Controller 2."
});

In the next tutorial we will discuss different Directives in AngularJS