To become an Outstanding AngularJs Developer - part 2

11. HTML DOM

The following directives are used to bind application data to the attributes of HTML DOM elements −

ng-disabled Directive

Add ng-disabled attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation.

<input type = "checkbox" ng-model = "enableDisableButton">Disable Button
<button ng-disabled = "enableDisableButton">Click Me!</button>

ng-show Directive

Add ng-show attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation.

<input type = "checkbox" ng-model = "showHide1">Show Button
<button ng-show = "showHide1">Click Me!</button>

ng-hide Directive

Add ng-hide attribute to an HTML button and pass it a model. Bind the model to a checkbox and see the variation.

<input type = "checkbox" ng-model = "showHide2">Hide Button
<button ng-hide = "showHide2">Click Me!</button>

ng-click Directive

Add ng-click attribute to an HTML button and update a model. Bind the model to HTML and see the variation.

<p>Total click: {{ clickCounter }}</p>
<button ng-click = "clickCounter = clickCounter + 1">Click Me!</button>

Example

The following example shows use of all the above mentioned directives.

testAngularJS.htm

<html>
   <head>
      <title>AngularJS HTML DOM</title>
   </head>

<body>
<h2>AngularJS Sample Application</h2>

  &lt;div ng-app = ""&gt;
     &lt;table border = "0"&gt;
        &lt;tr&gt;
           &lt;td&gt;&lt;input type = "checkbox" ng-model = "enableDisableButton"&gt;Disable Button&lt;/td&gt;
           &lt;td&gt;&lt;button ng-disabled = "enableDisableButton"&gt;Click Me!&lt;/button&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
           &lt;td&gt;&lt;input type = "checkbox" ng-model = "showHide1"&gt;Show Button&lt;/td&gt;
           &lt;td&gt;&lt;button ng-show = "showHide1"&gt;Click Me!&lt;/button&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
           &lt;td&gt;&lt;input type = "checkbox" ng-model = "showHide2"&gt;Hide Button&lt;/td&gt;
           &lt;td&gt;&lt;button ng-hide = "showHide2"&gt;Click Me!&lt;/button&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
           &lt;td&gt;&lt;p&gt;Total click: {{ clickCounter }}&lt;/p&gt;&lt;/td&gt;
           &lt;td&gt;&lt;button ng-click = "clickCounter = clickCounter + 1"&gt;Click Me!&lt;/button&gt;&lt;/td&gt;
        &lt;/tr&gt;
     &lt;/table&gt;
  &lt;/div&gt;
  
  &lt;script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"&gt;
  &lt;/script&gt;

</body>
</html>

Output

Open the file testAngularJS.htm in a web browser and see the result.

12. Modules

AngularJS supports modular approach. Modules are used to separate logic such as services, controllers, application etc. from the code and maintain the code clean. We define modules in separate js files and name them as per the module.js file. In the following example, we are going to create two modules −

  • Application Module − used to initialize an application with controller(s).
  • Controller Module − used to define the controller.

Application Module

Here is a file named mainApp.js that contains the following code −

var mainApp = angular.module(“mainApp”, []);

Here, we declare an application mainApp module using angular.module function and pass an empty array to it. This array generally contains dependent modules.

Controller Module

studentController.js

mainApp.controller(“studentController”, function($scope) {
$scope.student = {
firstName: “Mahesh”,
lastName: “Parashar”,
fees:500,

  subjects:[
     {name:'Physics',marks:70},
     {name:'Chemistry',marks:80},
     {name:'Math',marks:65},
     {name:'English',marks:75},
     {name:'Hindi',marks:67}
  ],
  fullName: function() {
     var studentObject;
     studentObject = $scope.student;
     return studentObject.firstName + " " + studentObject.lastName;
  }

};
});

Here, we declare a controller studentController module using mainApp.controller function.

Use Modules

<div ng-app = “mainApp” ng-controller = “studentController”>

<script src = “mainApp.js”></script>
<script src = “studentController.js”></script>

</div>

Here, we use application module using ng-app directive, and controller using ngcontroller directive. We import the mainApp.js and studentController.js in the main HTML page.

Example

The following example shows use of all the above mentioned modules.

testAngularJS.htm

<html>
<head>
<title>Angular JS Modules</title>
<script src = “https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”></script>
<script src = “/angularjs/src/module/mainApp.js”></script>
<script src = “/angularjs/src/module/studentController.js”></script>

  &lt;style&gt;
     table, th , td {
        border: 1px solid grey;
        border-collapse: collapse;
        padding: 5px;
     }
     table tr:nth-child(odd) {
        background-color: #f2f2f2;
     }
     table tr:nth-child(even) {
        background-color: #ffffff;
     }
  &lt;/style&gt;

</head>

<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = “mainApp” ng-controller = “studentController”>

     &lt;table border = "0"&gt;
        &lt;tr&gt;
           &lt;td&gt;Enter first name:&lt;/td&gt;
           &lt;td&gt;&lt;input type = "text" ng-model = "student.firstName"&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
           &lt;td&gt;Enter last name: &lt;/td&gt;
           &lt;td&gt;&lt;input type = "text" ng-model = "student.lastName"&gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
           &lt;td&gt;Name: &lt;/td&gt;
           &lt;td&gt;{{student.fullName()}}&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
           &lt;td&gt;Subject:&lt;/td&gt;
           
           &lt;td&gt;
              &lt;table&gt;
                 &lt;tr&gt;
                    &lt;th&gt;Name&lt;/th&gt;
                    &lt;th&gt;Marks&lt;/th&gt;
                 &lt;/tr&gt;
                 &lt;tr ng-repeat = "subject in student.subjects"&gt;
                    &lt;td&gt;{{ subject.name }}&lt;/td&gt;
                    &lt;td&gt;{{ subject.marks }}&lt;/td&gt;
                 &lt;/tr&gt;
              &lt;/table&gt;
           &lt;/td&gt;
        &lt;/tr&gt;
     &lt;/table&gt;
  &lt;/div&gt;

</body>
</html>

mainApp.js

var mainApp = angular.module(“mainApp”, []);

studentController.js

mainApp.controller(“studentController”, function($scope) {
$scope.student = {
firstName: “Mahesh”,
lastName: “Parashar”,
fees:500,

  subjects:[
     {name:'Physics',marks:70},
     {name:'Chemistry',marks:80},
     {name:'Math',marks:65},
     {name:'English',marks:75},
     {name:'Hindi',marks:67}
  ],
  fullName: function() {
     var studentObject;
     studentObject = $scope.student;
     return studentObject.firstName + " " + studentObject.lastName;
  }

};
});

Output

Open the file textAngularJS.htm in a web browser. See the result.

13. Forms

AngularJS enriches form filling and validation. We can use ng-click event to handle the click button and use $dirty and $invalid flags to do the validation in a seamless way. Use novalidate with a form declaration to disable any browser-specific validation. The form controls make heavy use of AngularJS events. Let us have a look at the events first.

Events

AngularJS provides multiple events associated with the HTML controls. For example, ng-click directive is generally associated with a button. AngularJS supports the following events −

  • ng-click
  • ng-dbl-click
  • ng-mousedown
  • ng-mouseup
  • ng-mouseenter
  • ng-mouseleave
  • ng-mousemove
  • ng-mouseover
  • ng-keydown
  • ng-keyup
  • ng-keypress
  • ng-change

ng-click

Reset data of a form using on-click directive of a button.

<input name = “firstname” type = “text” ng-model = “firstName” required>
<input name = “lastname” type = “text” ng-model = “lastName” required>
<input name = “email” type = “email” ng-model = “email” required>
<button ng-click = “reset()”>Reset</button>

<script>
function studentController($scope) {
$scope.reset = function() {
$scope.firstName = “Mahesh”;
$scope.lastName = “Parashar”;
$scope.email = “MaheshParashar@tutorialspoint.com”;
}

  $scope.reset();

}
</script>

Validate Data

The following can be used to track error.

  • $dirty − states that value has been changed.
  • $invalid − states that value entered is invalid.
  • $error − states the exact error.

Example

The following example will showcase all the above-mentioned directives.

testAngularJS.htm

<html>
<head>
<title>Angular JS Forms</title>
<script src = “https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”></script>

  &lt;style&gt;
     table, th , td {
        border: 1px solid grey;
        border-collapse: collapse;
        padding: 5px;
     }
     table tr:nth-child(odd) {
        background-color: #f2f2f2;
     }
     table tr:nth-child(even) {
        background-color: #ffffff;
     }
  &lt;/style&gt;

</head>
<body>

  &lt;h2&gt;AngularJS Sample Application&lt;/h2&gt;
  &lt;div ng-app = "mainApp" ng-controller = "studentController"&gt;
     
     &lt;form name = "studentForm" novalidate&gt;
        &lt;table border = "0"&gt;
           &lt;tr&gt;
              &lt;td&gt;Enter first name:&lt;/td&gt;
              &lt;td&gt;&lt;input name = "firstname" type = "text" ng-model = "firstName" required&gt;
                 &lt;span style = "color:red" ng-show = "studentForm.firstname.$dirty &amp;&amp; studentForm.firstname.$invalid"&gt;
                    &lt;span ng-show = "studentForm.firstname.$error.required"&gt;First Name is required.&lt;/span&gt;
                 &lt;/span&gt;
              &lt;/td&gt;
           &lt;/tr&gt;
           
           &lt;tr&gt;
              &lt;td&gt;Enter last name: &lt;/td&gt;
              &lt;td&gt;&lt;input name = "lastname"  type = "text" ng-model = "lastName" required&gt;
                 &lt;span style = "color:red" ng-show = "studentForm.lastname.$dirty &amp;&amp; studentForm.lastname.$invalid"&gt;
                    &lt;span ng-show = "studentForm.lastname.$error.required"&gt;Last Name is required.&lt;/span&gt;
                 &lt;/span&gt;
              &lt;/td&gt;
           &lt;/tr&gt;
           
           &lt;tr&gt;
              &lt;td&gt;Email: &lt;/td&gt;&lt;td&gt;&lt;input name = "email" type = "email" ng-model = "email" length = "100" required&gt;
                 &lt;span style = "color:red" ng-show = "studentForm.email.$dirty &amp;&amp; studentForm.email.$invalid"&gt;
                    &lt;span ng-show = "studentForm.email.$error.required"&gt;Email is required.&lt;/span&gt;
                    &lt;span ng-show = "studentForm.email.$error.email"&gt;Invalid email address.&lt;/span&gt;
                 &lt;/span&gt;
              &lt;/td&gt;
           &lt;/tr&gt;
           
           &lt;tr&gt;
              &lt;td&gt;
                 &lt;button ng-click = "reset()"&gt;Reset&lt;/button&gt;
              &lt;/td&gt;
              &lt;td&gt;
                 &lt;button ng-disabled = "studentForm.firstname.$dirty &amp;&amp;
                    studentForm.firstname.$invalid || studentForm.lastname.$dirty &amp;&amp;
                    studentForm.lastname.$invalid || studentForm.email.$dirty &amp;&amp;
                    studentForm.email.$invalid" ng-click="submit()"&gt;Submit&lt;/button&gt;
              &lt;/td&gt;
           &lt;/tr&gt;
				
        &lt;/table&gt;
     &lt;/form&gt;
  &lt;/div&gt;
  
  &lt;script&gt;
     var mainApp = angular.module("mainApp", []);
     
     mainApp.controller('studentController', function($scope) {
        $scope.reset = function() {
           $scope.firstName = "Mahesh";
           $scope.lastName = "Parashar";
           $scope.email = "MaheshParashar@tutorialspoint.com";
        }
        
        $scope.reset();
     });
  &lt;/script&gt;

</body>
</html>

Output

Open the file testAngularJS.htm in a web browser and see the result.

14. Includes

HTML does not support embedding HTML pages within the HTML page. To achieve this functionality, we can use one of the following options −

  • Using Ajax − Make a server call to get the corresponding HTML page and set it in the innerHTML of HTML control.
  • Using Server Side Includes − JSP, PHP and other web side server technologies can include HTML pages within a dynamic page.

Using AngularJS, we can embed HTML pages within an HTML page using ng-include directive.

<div ng-app = “” ng-controller = “studentController”>
<div ng-include = “‘main.htm’”></div>
<div ng-include = “‘subjects.htm’”></div>
</div>

Example

tryAngularJS.htm

<html>
<head>
<title>Angular JS Includes</title>
<script src = “https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”>
</script>

  &lt;style&gt;
     table, th , td {
        border: 1px solid grey;
        border-collapse: collapse;
        padding: 5px;
     }
     table tr:nth-child(odd) {
        background-color: #f2f2f2;
     }
     table tr:nth-child(even) {
        background-color: #ffffff;
     }
  &lt;/style&gt;

</head>

<body>
<h2>AngularJS Sample Application</h2>

  &lt;div ng-app = "mainApp" ng-controller = "studentController"&gt;
     &lt;div ng-include = "'/angularjs/src/include/main.htm'"&gt;&lt;/div&gt;
     &lt;div ng-include = "'/angularjs/src/include/subjects.htm'"&gt;&lt;/div&gt;
  &lt;/div&gt;
  
  &lt;script&gt;
     var mainApp = angular.module("mainApp", []);
     
     mainApp.controller('studentController', function($scope) {
        $scope.student = {
           firstName: "Mahesh",
           lastName: "Parashar",
           fees:500,
           
           subjects:[
              {name:'Physics',marks:70},
              {name:'Chemistry',marks:80},
              {name:'Math',marks:65},
              {name:'English',marks:75},
              {name:'Hindi',marks:67}
           ],
           fullName: function() {
              var studentObject;
              studentObject = $scope.student;
              return studentObject.firstName + " " + studentObject.lastName;
           }
        };
     });
  &lt;/script&gt;

</body>
</html>

main.htm

<table border = “0”>
<tr>
<td>Enter first name:</td>
<td><input type = “text” ng-model = “student.firstName”></td>
</tr>

<tr>
<td>Enter last name: </td>
<td><input type = “text” ng-model = “student.lastName”></td>
</tr>

<tr>
<td>Name: </td>
<td>{{student.fullName()}}</td>
</tr>
</table>

subjects.htm

<p>Subjects:</p>
<table>
<tr>
<th>Name</th>
<th>Marks</th>
</tr>

<tr ng-repeat = “subject in student.subjects”>
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table>

Output

To execute this example, you need to deploy testAngularJS.htm, main.htm, and subjects.htm to a web server. Open the file testAngularJS.htm using the URL of your server in a web browser and see the result.

15. Ajax

AngularJS provides $http control which works as a service to read data from the server. The server makes a database call to get the desired records. AngularJS needs data in JSON format. Once the data is ready, $http can be used to get the data from server in the following manner −

function studentController($scope,$https:) {
var url = “data.txt”;

$https:.get(url).success( function(response) {
$scope.students = response;
});
}

Here, the file data.txt contains student records. $http service makes an ajax call and sets response to its property students. students model can be used to draw tables in HTML.

Examples

data.txt

[
{
“Name” : “Mahesh Parashar”,
“RollNo” : 101,
“Percentage” : “80%”
},
{
“Name” : “Dinkar Kad”,
“RollNo” : 201,
“Percentage” : “70%”
},
{
“Name” : “Robert”,
“RollNo” : 191,
“Percentage” : “75%”
},
{
“Name” : “Julian Joe”,
“RollNo” : 111,
“Percentage” : “77%”
}
]

testAngularJS.htm

<html>
<head>
<title>Angular JS Includes</title>

  &lt;style&gt;
     table, th , td {
        border: 1px solid grey;
        border-collapse: collapse;
        padding: 5px;
     }
     table tr:nth-child(odd) {
        background-color: #f2f2f2;
     }
     table tr:nth-child(even) {
        background-color: #ffffff;
     }
  &lt;/style&gt;

</head>

<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = “” ng-controller = “studentController”>

     &lt;table&gt;
        &lt;tr&gt;
           &lt;th&gt;Name&lt;/th&gt;
           &lt;th&gt;Roll No&lt;/th&gt;
           &lt;th&gt;Percentage&lt;/th&gt;
        &lt;/tr&gt;
     
        &lt;tr ng-repeat = "student in students"&gt;
           &lt;td&gt;{{ student.Name }}&lt;/td&gt;
           &lt;td&gt;{{ student.RollNo }}&lt;/td&gt;
           &lt;td&gt;{{ student.Percentage }}&lt;/td&gt;
        &lt;/tr&gt;
     &lt;/table&gt;
  &lt;/div&gt;
  
  &lt;script&gt;
     function studentController($scope,$http) {
        var url = "/data.txt";

        $http.get(url).then( function(response) {
           $scope.students = response.data;
        });
     }
  &lt;/script&gt;
  
  &lt;script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"&gt;
  &lt;/script&gt;

</body>
</html>

Output

To execute this example, you need to deploy testAngularJS.htm and data.txt file to a web server. Open the file testAngularJS.htm using the URL of your server in a web browser and see the result.

16. Views

AngularJS supports Single Page Application via multiple views on a single page. To do this, AngularJS has provided ng-view and ng-template directives, and $routeProvider services.

ng-view Directive

The ng-view directive simply creates a place holder where a corresponding view (HTML or ng-template view) can be placed based on the configuration.

Usage

Define a div with ng-view within the main module.

<div ng-app = “mainApp”>

<div ng-view></div>

</div>

ng-template Directive

The ng-template directive is used to create an HTML view using script tag. It contains id attribute which is used by $routeProvider to map a view with a controller.

Usage

Define a script block with type as ng-template within the main module.

<div ng-app = “mainApp”>

<script type = “text/ng-template” id = “addStudent.htm”>
<h2> Add Student </h2>
{{message}}
</script>

</div>

$routeProvider Service

The $routeProvider is a key service which sets the configuration of URLs, maps them with the corresponding HTML page or ng-template, and attaches a controller with the same.

Usage 1

Define a script block with type as ng-template within the main module.

<div ng-app = “mainApp”>

<script type = “text/ng-template” id = “addStudent.htm”>
<h2> Add Student </h2>
{{message}}
</script>
</div>

Usage 2

Define a script block with main module and set the routing configuration.

var mainApp = angular.module(“mainApp”, [‘ngRoute’]);

mainApp.config([‘$routeProvider’, function($routeProvider) {
$routeProvider

.when(‘/addStudent’, {
templateUrl: ‘addStudent.htm’, controller: ‘AddStudentController’
})
.when(‘/viewStudents’, {
templateUrl: ‘viewStudents.htm’, controller: ‘ViewStudentsController’
})
.otherwise ({
redirectTo: ‘/addStudent’
});

}]);

The following points are important to be considered in the above example −

  • $routeProvider is defined as a function under config of mainApp module using key as ‘$routeProvider’.
  • $routeProvider.when defines a URL “/addStudent”, which is mapped to “addStudent.htm”. addStudent.htm should be present in the same path as main HTML page. If the HTML page is not defined, then ng-template needs to be used with id=“addStudent.htm”. We used ng-template.
  • “otherwise” is used to set the default view.
  • “controller” is used to set the corresponding controller for the view.

Example

The following example shows the use of all the above-mentioned directives.

testAngularJS.htm

<html>
<head>
<title>Angular JS Views</title>
<script src = “https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”></script>
<script src = “https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js”>
</script>
</head>

<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = “mainApp”>
<p><a href = “#addStudent”>Add Student</a></p>
<p><a href = “#viewStudents”>View Students</a></p>
<div ng-view></div>

     &lt;script type = "text/ng-template" id = "addStudent.htm"&gt;
        &lt;h2&gt; Add Student &lt;/h2&gt;
        {{message}}
     &lt;/script&gt;
     
     &lt;script type = "text/ng-template" id = "viewStudents.htm"&gt;
        &lt;h2&gt; View Students &lt;/h2&gt;
        {{message}}
     &lt;/script&gt;
  &lt;/div&gt;
  
  &lt;script&gt;
     var mainApp = angular.module("mainApp", ['ngRoute']);
     mainApp.config(['$routeProvider', function($routeProvider) {
        $routeProvider
        
        .when('/addStudent', {
           templateUrl: 'addStudent.htm',
           controller: 'AddStudentController'
        })
        .when('/viewStudents', {
           templateUrl: 'viewStudents.htm',
           controller: 'ViewStudentsController'
        })
        .otherwise({
           redirectTo: '/addStudent'
        });
     }]);
     mainApp.controller('AddStudentController', function($scope) {
        $scope.message = "This page will be used to display add student form";
     });
     mainApp.controller('ViewStudentsController', function($scope) {
        $scope.message = "This page will be used to display all the students";
     });
  &lt;/script&gt;

</body>
</html>

Output

Open the file testAngularJS.htm in a web browser and see the result.

17. Scopes

Scope is a special JavaScript object that connects controller with views. Scope contains model data. In controllers, model data is accessed via $scope object.

<script>
var mainApp = angular.module(“mainApp”, []);

mainApp.controller(“shapeController”, function($scope) {
$scope.message = “In shape controller”;
$scope.type = “Shape”;
});
</script>

The following important points are considered in above example −

  • The $scope is passed as first argument to controller during its constructor definition.
  • The $scope.message and $scope.type are the models which are used in the HTML page.
  • We assign values to models that are reflected in the application module, whose controller is shapeController.
  • We can define functions in $scope.

Scope Inheritance

Scope is controller-specific. If we define nested controllers, then the child controller inherits the scope of its parent controller.

<script>
var mainApp = angular.module(“mainApp”, []);

mainApp.controller(“shapeController”, function($scope) {
$scope.message = “In shape controller”;
$scope.type = “Shape”;
});
mainApp.controller(“circleController”, function($scope) {
$scope.message = “In circle controller”;
});

</script>

The following important points are considered in above example −

  • We assign values to the models in shapeController.
  • We override message in child controller named circleController. When message is used within the module of controller named circleController, the overridden message is used.

Example

The following example shows use of all the above mentioned directives.

testAngularJS.htm

<html>
<head>
<title>Angular JS Forms</title>
</head>

<body>
<h2>AngularJS Sample Application</h2>

  &lt;div ng-app = "mainApp" ng-controller = "shapeController"&gt;
     &lt;p&gt;{{message}} &lt;br/&gt; {{type}} &lt;/p&gt;
     
     &lt;div ng-controller = "circleController"&gt;
        &lt;p&gt;{{message}} &lt;br/&gt; {{type}} &lt;/p&gt;
     &lt;/div&gt;
     
     &lt;div ng-controller = "squareController"&gt;
        &lt;p&gt;{{message}} &lt;br/&gt; {{type}} &lt;/p&gt;
     &lt;/div&gt;
		
  &lt;/div&gt;
  &lt;script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"&gt;
  &lt;/script&gt;
  
  &lt;script&gt;
     var mainApp = angular.module("mainApp", []);
     
     mainApp.controller("shapeController", function($scope) {
        $scope.message = "In shape controller";
        $scope.type = "Shape";
     });
     mainApp.controller("circleController", function($scope) {
        $scope.message = "In circle controller";
     });
     mainApp.controller("squareController", function($scope) {
        $scope.message = "In square controller";
        $scope.type = "Square";
     });
		
  &lt;/script&gt;

</body>
</html>

Output

Open the file testAngularJS.htm in a web browser and see the result.

18. Services

AngularJS supports the concept of Separation of Concerns using services architecture. Services are JavaScript functions, which are responsible to perform only specific tasks. This makes them individual entities which are maintainable and testable. The controllers and filters can call them on requirement basis. Services are normally injected using the dependency injection mechanism of AngularJS.

AngularJS provides many inbuilt services. For example, $http, $route, $window, $location, etc. Each service is responsible for a specific task such as the $http is used to make ajax call to get the server data, the $route is used to define the routing information, and so on. The inbuilt services are always prefixed with $ symbol.

There are two ways to create a service −

  • Factory
  • Service

Using Factory Method

In this method, we first define a factory and then assign method to it.

var mainApp = angular.module(“mainApp”, []);
mainApp.factory(‘MathService’, function() {
var factory = {};

factory.multiply = function(a, b) {
return a * b
}

return factory;
});

Using Service Method

In this method, we define a service and then assign method to it. We also inject an already available service to it.

mainApp.service(‘CalcService’, function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});

Example

The following example shows use of all the above mentioned directives −

testAngularJS.htm

<html>
<head>
<title>Angular JS Services</title>
<script src = “https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js”>
</script>
</head>

<body>
<h2>AngularJS Sample Application</h2>

  &lt;div ng-app = "mainApp" ng-controller = "CalcController"&gt;
     &lt;p&gt;Enter a number: &lt;input type = "number" ng-model = "number" /&gt;&lt;/p&gt;
     &lt;button ng-click = "square()"&gt;X&lt;sup&gt;2&lt;/sup&gt;&lt;/button&gt;
     &lt;p&gt;Result: {{result}}&lt;/p&gt;
  &lt;/div&gt;
  
  &lt;script&gt;
     var mainApp = angular.module("mainApp", []);
     
     mainApp.factory('MathService', function() {
        var factory = {};
        
        factory.multiply = function(a, b) {
           return a * b
        }
        return factory;
     });
     mainApp.service('CalcService', function(MathService) {
        this.square = function(a) {
           return MathService.multiply(a,a);
        }
     });
     mainApp.controller('CalcController', function($scope, CalcService) {
        $scope.square = function() {
           $scope.result = CalcService.square($scope.number);
        }
     });
  &lt;/script&gt;

</body>
</html>

Output

Open the file testAngularJS.htm in a web browser and see the result.

19. Dependency Injection

Dependency Injection is a software design in which components are given their dependencies instead of hard coding them within the component. It relieves a component from locating the dependency and makes dependencies configurable. It also helps in making components reusable, maintainable and testable.

AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.

  • Value
  • Factory
  • Service
  • Provider
  • Constant

Value

Value is a simple JavaScript object, which is required to pass values to the controller during config phase (config phase is when AngularJS bootstraps itself).

//define a module
var mainApp = angular.module(“mainApp”, []);

//create a value object as “defaultInput” and pass it a data.
mainApp.value(“defaultInput”, 5);

//inject the value in the controller using its name “defaultInput”
mainApp.controller(‘CalcController’, function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);

$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});

Factory

Factory is a function which is used to return value. It creates a value on demand whenever a service or a controller requires it. It generally uses a factory function to calculate and return the value.

//define a module
var mainApp = angular.module(“mainApp”, []);

//create a factory “MathService” which provides a method multiply to return multiplication of two numbers
mainApp.factory(‘MathService’, function() {
var factory = {};

factory.multiply = function(a, b) {
return a * b
}
return factory;
});

//inject the factory “MathService” in a service to utilize the multiply method of factory.
mainApp.service(‘CalcService’, function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});

Service

Service is a singleton JavaScript object containing a set of functions to perform certain tasks. Service is defined using service() function and it is then injected into the controllers.

//define a module
var mainApp = angular.module(“mainApp”, []);

//create a service which defines a method square to return square of a number.
mainApp.service(‘CalcService’, function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});

//inject the service “CalcService” into the controller
mainApp.controller(‘CalcController’, function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);

$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});

Provider

Provider is used by AngularJS internally to create services, factory, etc. during the config phase. The following script can be used to create MathService that we created earlier. Provider is a special factory method with get() method which is used to return the value/service/factory.

//define a module
var mainApp = angular.module(“mainApp”, []);

//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide) {
$provide.provider(‘MathService’, function() {
this.$get = function() {
var factory = {};

     factory.multiply = function(a, b) {
        return a * b; 
     }
     return factory;
  };

});
});

Constant

Constants are used to pass values at the config phase considering the fact that value cannot be used during the config phase.

mainApp.constant(“configParam”, “constant value”);

Example

The following example shows the use of all the above-mentioned directives −

testAngularJS.htm

<html>
<head>
<title>AngularJS Dependency Injection</title>
</head>

<body>
<h2>AngularJS Sample Application</h2>

  &lt;div ng-app = "mainApp" ng-controller = "CalcController"&gt;
     &lt;p&gt;Enter a number: &lt;input type = "number" ng-model = "number" /&gt;&lt;/p&gt;
     &lt;button ng-click = "square()"&gt;X&lt;sup&gt;2&lt;/sup&gt;&lt;/button&gt;
     &lt;p&gt;Result: {{result}}&lt;/p&gt;
  &lt;/div&gt;
  
  &lt;script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"&gt;
  &lt;/script&gt;
  
  &lt;script&gt;
     var mainApp = angular.module("mainApp", []);
     
     mainApp.config(function($provide) {
        $provide.provider('MathService', function() {
           this.$get = function() {
              var factory = {};
              
              factory.multiply = function(a, b) {
                 return a * b;
              }
              return factory;
           };
        });
     });
		
     mainApp.value("defaultInput", 5);
     
     mainApp.factory('MathService', function() {
        var factory = {};
        
        factory.multiply = function(a, b) {
           return a * b;
        }
        return factory;
     });
     mainApp.service('CalcService', function(MathService) {
        this.square = function(a) {
           return MathService.multiply(a,a);
        }
     });
     mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
        $scope.number = defaultInput;
        $scope.result = CalcService.square($scope.number);

        $scope.square = function() {
           $scope.result = CalcService.square($scope.number);
        }
     });
  &lt;/script&gt;

</body>
</html>

Output

Open testAngularJS.htm in a web browser and see the result.

20. Custom Directives

Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using “directive” function. A custom directive simply replaces the element for which it is activated. AngularJS application during bootstrap finds the matching elements and do one time activity using its compile() method of the custom directive then process the element using link() method of the custom directive based on the scope of the directive. AngularJS provides support to create custom directives for following type of elements.

  • Element directives − Directive activates when a matching element is encountered.
  • Attribute − Directive activates when a matching attribute is encountered.
  • CSS − Directive activates when a matching css style is encountered.
  • Comment − Directive activates when a matching comment is encountered.

Understanding Custom Directive

Define custom html tags.

<student name = “Mahesh”></student><br/>
<student name = “Piyush”></student>

Define custom directive to handle above custom html tags.

var mainApp = angular.module(“mainApp”, []);

//Create a directive, first parameter is the html element to be attached.
//We are attaching student html tag.
//This directive will be activated as soon as any student element is encountered in html

mainApp.directive(‘student’, function() {
//define the directive object
var directive = {};

//restrict = E, signifies that directive is Element directive
directive.restrict = ‘E’;

//template replaces the complete element with its text.
directive.template = “Student: <b>{{student.name}}</b> ,
Roll No: <b>{{student.rollno}}</b>”;

//scope is used to distinguish each student element based on criteria.
directive.scope = {
student : “=name”
}

//compile is called during application initialization. AngularJS calls
it once when html page is loaded.

directive.compile = function(element, attributes) {
element.css(“border”, “1px solid #cccccc”);

  //linkFunction is linked with each element with scope to get the element specific data.
  var linkFunction = function($scope, element, attributes) {
     element.html("Student: &lt;b&gt;"+$scope.student.name +"&lt;/b&gt; , 
        Roll No: &lt;b&gt;"+$scope.student.rollno+"&lt;/b&gt;&lt;br/&gt;");
     element.css("background-color", "#ff00ff");
  }
  return linkFunction;

}

return directive;
});

Define controller to update the scope for directive. Here we are using name attribute’s value as scope’s child.

mainApp.controller(‘StudentController’, function($scope) {
$scope.Mahesh = {};
$scope.Mahesh.name = “Mahesh Parashar”;
$scope.Mahesh.rollno = 1;

$scope.Piyush = {};
$scope.Piyush.name = “Piyush Parashar”;
$scope.Piyush.rollno = 2;
});

Example

<html>
<head>
<title>Angular JS Custom Directives</title>
</head>

<body>
<h2>AngularJS Sample Application</h2>

  &lt;div ng-app = "mainApp" ng-controller = "StudentController"&gt;
     &lt;student name = "Mahesh"&gt;&lt;/student&gt;&lt;br/&gt;
     &lt;student name = "Piyush"&gt;&lt;/student&gt;
  &lt;/div&gt;
	
  &lt;script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"&gt;
  &lt;/script&gt;
  
  &lt;script&gt;
     var mainApp = angular.module("mainApp", []);
     
     mainApp.directive('student', function() {
        var directive = {};
        directive.restrict = 'E';
        directive.template = "Student: &lt;b&gt;{{student.name}}&lt;/b&gt; , 
           Roll No: &lt;b&gt;{{student.rollno}}&lt;/b&gt;";
        
        directive.scope = {
           student : "=name"
        }
        directive.compile = function(element, attributes) {
           element.css("border", "1px solid #cccccc");
           
           var linkFunction = function($scope, element, attributes) {
              element.html("Student: &lt;b&gt;"+$scope.student.name +"&lt;/b&gt; , 
                 Roll No: &lt;b&gt;"+$scope.student.rollno+"&lt;/b&gt;&lt;br/&gt;");
              element.css("background-color", "#ff00ff");
           }
           return linkFunction;
        }
        
        return directive;
     });
     mainApp.controller('StudentController', function($scope) {
        $scope.Mahesh = {};
        $scope.Mahesh.name = "Mahesh Parashar";
        $scope.Mahesh.rollno  = 1;

        $scope.Piyush = {};
        $scope.Piyush.name = "Piyush Parashar";
        $scope.Piyush.rollno  = 2;
     });
  &lt;/script&gt;

</body>
</html>

Output

Open textAngularJS.htm in a web browser. See the result.

21. Internationalization

AngularJS supports inbuilt internationalization for three types of filters : Currency, Date, and Numbers. We only need to incorporate corresponding java script according to locale of the country. By default, it considers the locale of the browser. For example, for Danish locale, use the following script −

<script src = “https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js”>
</script>

Example Using Danish Locale

testAngularJS.htm

<html>
<head>
<title>Angular JS Forms</title>
</head>

<body>
<h2>AngularJS Sample Application</h2>

  &lt;div ng-app = "mainApp" ng-controller = "StudentController"&gt;
     {{fees | currency }}  &lt;br/&gt;&lt;br/&gt;
     {{admissiondate | date }}  &lt;br/&gt;&lt;br/&gt;
     {{rollno | number }}
  &lt;/div&gt;
	
  &lt;script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"&gt;
  &lt;/script&gt;
  &lt;script src = "https://code.angularjs.org/1.3.14/i18n/angular-locale_da-dk.js"&gt;
  &lt;/script&gt;
  
  &lt;script&gt;
     var mainApp = angular.module("mainApp", []);
     
     mainApp.controller('StudentController', function($scope) {
        $scope.fees = 100;
        $scope.admissiondate  = new Date();
        $scope.rollno = 123.45;
     });
  &lt;/script&gt;

</body>
</html>

Output

Open the file testAngularJS.htm in a web browser and see the result.

Example Using Browser Locale

testAngularJS.htm

<html>
<head>
<title>Angular JS Forms</title>
</head>

<body>
<h2>AngularJS Sample Application</h2>

  &lt;div ng-app = "mainApp" ng-controller = "StudentController"&gt;
     {{fees | currency }}  &lt;br/&gt;&lt;br/&gt;
     {{admissiondate | date }}  &lt;br/&gt;&lt;br/&gt;
     {{rollno | number }}
  &lt;/div&gt;
	
  &lt;script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"&gt;
  &lt;/script&gt;
  &lt;!-- &lt;script src = "https://code.angularjs.org/1.3.14/i18n/angular-locale_da-dk.js"&gt;
  &lt;/script&gt; --&gt;
  
  &lt;script&gt;
     var mainApp = angular.module("mainApp", []);
     
     mainApp.controller('StudentController', function($scope) {
        $scope.fees = 100;
        $scope.admissiondate  = new Date();
        $scope.rollno = 123.45;
     });
  &lt;/script&gt;

</body>
</html>

Output

Open the file testAngularJS.htm in a web browser and see the result.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!

#angular-js #angular #web-development #devops

To become an Outstanding AngularJs Developer - part 2
1 Likes24.75 GEEK