AngularJS Modules

We have covered most of the fundamental AngularJS concepts including views, controllers, models etc. In this article we shall study AngularJS modules. AngularJS modules act as container for controllers and different parts of the application. Modules are basically used to organize application components in a way where they can seamlessly work without depending upon each other. To create AngularJS modules, “angular.module” function is used. Take look at folling

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="NewApp" ng-controller="NewCtrl">

    <input type="text" ng-model="Name">
     <input type="text" ng-model="Age">
{{ Name + " " + Age}}
</div>

<script>

var myapp = angular.module("NewApp", []);

myapp.controller("NewCtrl", function($scope) {
    $scope.Name = "";
    $scope.Age = "";
});

</script>

</body>
</html>

Download the code Try the code

Take a careful look at the script section of the above code. Here we create a module via “angular.module” function. The function takes two parameters, the first parameter is specifies the html element in which AngularJS application shall run. It is “NewApp” in above code. Now the element in which you want to run the AngularJS application must have this “NewApp” as value for the “ng-app” directive. The “angular.module” function returns a handler. In the above code “myapp” variable stores this handler. You can create services, controllers, directives etc in the module via its handler.

In the above code we create a controller named “NewCtrl” which contains two variables Name and Age. Now come back to the view inside the div which has “ng-app” directive. Inside the div we bind these two variables with two text boxes. As soon as the value in text box changes, it is printed on the page.

Adding Directive To Modules

In last example we added controller to the module. Similarly, We can also add directives to AngularJS Modules. Take a look at the following example.

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>

<div ng-app="NewApp" custom-directive></div>

<script> 
var app = angular.module("NewApp", []);

app.directive("customDirective", function() {
    return {
        template : "I am custom directive made by a module."
    };
});
</script>

</body>
</html>

Download the code Try the code

In the above code, we have called “directive” function on modules handler variable. Directive function takes two parameters: the name of the directive and the function. Inside the function, you can add the template of the directive. In the above code, template contains a simple message. Therefore, whenever you add this directive to an html element, the inner html of the message will change to the text in the template.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .