Custom Service in AngularJS

In AngularJs, like other features, one of the main features is service provider. In Angular Js, service is basically a single tone objects which used to perform for a specific tasks.

Why Need Service 

Basically Angular JS services represents the separation of concern using service architectures. Actually AngularJs services consists of JavaScript functions and also used for a particular tasks. May be one service contains multiple JavaScript function for different task. But precisely it is important that each of the function must be perform simple responsibility. Actually in this way we can easily maintain and test the code. We need to call the services in controllers, directives and filters as per our requirement. Services are normally injected using dependency injection mechanism of AngularJs. Actually angular js provides many inbuilt services for our uses, eg. $http, $route, $location etc. Each service is responsible for a specific work as example , $http is used for make ajax request call to get or post the server data. $route is defined for routing information.

How to Create Service

There are two ways of creating services –

  1. Factory – In this method, we need to define factory first and then assign method to it.
    1. testapp.factory(‘testservice’, function(){  
    2.   
    3.    return {  
    4.   
    5.       method : function(){  
    6.   
    7.          --------  
    8.   
    9.          --------  
    10.   
    11.       },  
    12.   
    13.       method : function(){  
    14.   
    15.          --------  
    16.   
    17.          --------  
    18.   
    19.       }  
    20.   
    21.    };  
    22.   
    23. }); 
  2. Service – In this method, we need to define service first and then assign method to it.
    1. testapp.service(‘testservice’, function(){  
    2.   
    3. this.method1 = function(){  
    4.   
    5. ……………………………  
    6.   
    7. }  
    8.   
    9. this.method1 = function(){  
    10.   
    11. ……………………………  
    12.   
    13. }  
    14.   
    15. });  
For doing this, we want to create calculator type program using service. For this we first create a javascript file named SampleService.js and write down the below code -
  1. 'use strict';    
  2.     
  3. var testApp = angular.module('TestApp', []);    
  4.     
  5. testApp.factory("calculate", function () {    
  6.     return {    
  7.         add: function (args1, args2) {    
  8.             return args1 + args2;    
  9.         },    
  10.         subtract: function (args1, args2) {    
  11.             return args1 - args2;    
  12.         },    
  13.         multiply: function (args1, args2) {    
  14.             return args1 * args2;    
  15.         },    
  16.         divide: function (args1, args2) {    
  17.             return args1 / args2;    
  18.         },    
  19.     };    
  20. }); 
Now add another javascript file named indexcontroller.js and write down the below code -
  1. testApp.controller('IndexController', ['$http''calculate', function ($http, calculate) {    
  2.     var self = this;    
  3.     
  4.     self.message = 'Angular Service';    
  5.     
  6.     self.fnAdd = function () {    
  7.         self.resultNumber = calculate.add(parseFloat(self.firstNumber), parseFloat(self.secondNumber));    
  8.     }    
  9.         
  10.     self.fnSub = function () {    
  11.         self.resultNumber = calculate.subtract(parseFloat(self.firstNumber), parseFloat(self.secondNumber));    
  12.     }    
  13.     
  14.     self.fnMultiply = function () {    
  15.         self.resultNumber = calculate.multiply(parseFloat(self.firstNumber), parseFloat(self.secondNumber));    
  16.     }    
  17.     
  18.     self.fnDivide = function () {    
  19.         self.resultNumber = calculate.divide(parseFloat(self.firstNumber), parseFloat(self.secondNumber));    
  20.     }    
  21.     
  22. }]);  
Now, add the html file named index.html and write down the below code -
  1. <!DOCTYPE html>    
  2. <html xmlns="http://www.w3.org/1999/xhtml">    
  3. <head>    
  4.     <title>Directive Types</title>    
  5.     <link href="../../RefStyle/bootstrap.min.css" rel="stylesheet" />    
  6.     <script src="../../Scripts/angular.min.js"></script>    
  7.     <script src="SampleService.js"></script>    
  8.     <script src="IndexController.js"></script>    
  9.     
  10. </head>    
  11. <body data-ng-app="TestApp" data-ng-controller="IndexController as model">    
  12.     <div class="row animated fadeInRight">    
  13.         <div class="col-lg-12">    
  14.             <div class="rowDiv">    
  15.                 <h3>{{model.message}}</h3>    
  16.             </div>    
  17.         </div>    
  18.         <div class="rowDiv">    
  19.             <div class="col-lg-3">    
  20.                 First Number    
  21.             </div>    
  22.             <div class="col-lg-9">    
  23.                 <input type="text" data-ng-model="model.firstNumber" />    
  24.             </div>    
  25.         </div>    
  26.         <div class="rowDiv">    
  27.             <div class="col-lg-3">    
  28.                 Second Number    
  29.             </div>    
  30.             <div class="col-lg-9">    
  31.                 <input type="text" data-ng-model="model.secondNumber" />    
  32.             </div>    
  33.         </div>    
  34.         <div class="rowDiv">    
  35.             <div class="col-lg-3">    
  36.                 Result    
  37.             </div>    
  38.             <div class="col-lg-9">    
  39.                 <input type="text" data-ng-model="model.resultNumber" readonly />    
  40.             </div>    
  41.         </div>    
  42.         <div class="rowDiv">    
  43.             <div class="col-lg-3">    
  44.     
  45.             </div>    
  46.             <div class="col-lg-9">    
  47.                 <input type="button" value="+" data-ng-click="model.fnAdd();" />    
  48.                 <input type="button" value="-" data-ng-click="model.fnSub();" />    
  49.                 <input type="button" value="x" data-ng-click="model.fnMultiply();" />    
  50.                 <input type="button" value="/" data-ng-click="model.fnDivide();" />    
  51.             </div>    
  52.         </div>    
  53.     </div>    
  54. </body>    
  55. </html>   
Now run the code and output will be same -