×

Html & Html5

The World's best Software Development Study Portal

AngularJS Module


The Angular JS Modules defines the functionality of the application which is applied on the entire HTML page. It helps to link many components.So,it is just a group of related components. It is a container which consists of different parts like controllers and directives.

Note:This module should be made in a normal HTML files like index.html and no need to create a new project in visual studio for this section.




How to create a Module:


Step 1.Create a Module
var app = angular.module("myApp", []);

Step 2. Add a Controller
app.controller("myCtrl", function($scope) {
$scope.firstName = "IT training classes";
$scope.lastName = "Gurugram"; });





Adding a Controller:


Add a controller to your application and refer to the controller with the ng-controller directive.For Example:

<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.firstName = "Marky";
  $scope.lastName = "Steven";
});
</script>




Adding a Directive:

Angular JS has a set of built-in directives which you can use to add functionality to your application.For Example:

<div ng-app="myApp" It-test-directive></div>
<script>
var app = angular.module("myApp", []);
app.directive("ItTestDirective", function() {
  return {
    template : "It was made in a directive constructor!"
  };
});
</script>


Note:
It makes sure the module and component files are in the same folder otherwise provide the path in whuch they are saved and run.



Modules and Controllers in Files

It is common in AngularJS applications to 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>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<script src="myApp.js"></script>
<script src="myCtrl.js"></script>
</body>
</html>




myApp.js


var app = angular.module("myApp", []);

Note:The [] parameter in the module definition can be used to define dependent modules. Without the [] parameter, you are not creating a new module, but retrieving an existing one.




myCtrl.js


app.controller("myCtrl", function($scope) {
  $scope.firstName = "Marky";
  $scope.lastName= "Steven";
});




Note: Here"myApp" parameter refers to an HTML element in which the application will run.