Google News
logo
AngularJS Modules
An AngularJS module defines an application. It's a container for the different parts of your application like controller, services, filters, directives, factories etc. It supports separation of concern using modules.

The angularJS module is used to Main() method. Controller always belongs to a module.
Creating a Module
AngularJS module is created by using the AngularJS function angular.module
<div ng-app="myApp">...</div>
 
<script type="text/javascript">
var app = angular.module("myApp", []); 
</script

Here, "myApp" specifies an HTML element in which the application will run.

Now we can add controllers, directives, filters, and more, to AngularJS application.

Adding controller to a module
Add a controller to your angularjs application, and refer to the controller with the ng-controller directive :
<!DOCTYPE html>
<html>
<head>
    <title>Adding controller to a module</title>
    <script type="text/javascript" src="js/angular.min.js"></script>
</head>
 
<body>
 
<div ng-app="myApp" ng-controller="myCtrl">
 
<h4> {{ firstName + " " + lastName }} </h4>
 
</div>
 
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
    $scope.firstName = "V V Ramana";
    $scope.lastName = "Reddy";
});
</script>
 
</body>
</html>
Output :
Adding a Directive
AnglarJS directives are used to add functionality to your application. You can also add your own directives for your applications.
<!DOCTYPE html>
<html>
<head>
    <title>Adding a Directive</title>
    <script type="text/javascript" src="js/angular.min.js"></script>
</head>
 
<body>
 
<div ng-app="myApp" w3-test-directive></div>
 
<script type="text/javascript">
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
    return {
        template : "This is a sample directive constructor!"
    };
});
</script>
 
</body>
</html>
Output :
Modules and controllers in file

In AngularJS applications, you can put the module and the controllers in JavaScript files.

In this example, "myApp.js" contains an application module definition, while "myCtrl.js" contains the controller :

<!DOCTYPE html>
<html>
<head>
    <title>Modules and controllers in file</title>
    <script type="text/javascript" src="js/angular.min.js"></script>
</head>
 
<body>
 
<div ng-app="myApp" ng-controller="myCtrl">
 
<h4> {{ firstName + " " + lastName }} </h4>
 
</div>
 
<script src="myApp.js"></script>
<script src="myCtrl.js"></script>
 
</body>
</html>
myApp.js
var app = angular.module("myApp", []);
myCtrl.js
app.controller("myCtrl", function($scope) {
    $scope.firstName = "V V Ramana";
    $scope.lastName= "Reddy";
});
Output :