Creating custom service in AngularJS

Concept of services in angular can be confusing initially if you come from background of frameworks / languages which support SOA or various kind of web / window services.I am from .NET background and on hearing word service the first thing that came to my mind was a WCF service.Well fortunately the concept of service in angular is quite simple .

Service in AngularJS is a set of reusable functionality which can be used across application.Few of the inbuilt services which angular provides include http calls ($http), routing ($route),window related ($window),url related ($location) etc. Two points that you should remember about services are that

  • Service are singleton objects
  • Service are lazily instantiated.

If you have used any of the general purpose languages like C++,C# ,Java etc than service would be similar to a static or a singleton class having some common functionality like logging , Timer ,scheduling etc.

In case you are new to writing code in angular you can visit my earlier post which outlines from start how to build your first application in AngularJS and also explain the concepts involved (including using one of the internal or inbuilt angular service viz. $http).Also you can take this pluralsight course on getting started with Angular JS by Scott Allen.

CalculationService : An example of custom service in AngularJS

In this post i’ll be developing a very simple service  which will perform common functionality of addition,subtraction,division and multiplication.

Below is the basic application which I have written which would be using our custom service.This application will be used to perform arithmetic operation and has a very basic user interface as shown below.

image

Here is the code written so far for user interface and controller.

index.html

<!DOCTYPE html>
<html>

 <head>
 <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
 <link rel="stylesheet" href="style.css" />
 <script src="script.js"></script>
 </head>

 <body ng-app="CalculationApp" ng-controller="CalculationController">
 <div>
 <h2>Calculation Service</h2>

 <input type="text" name="Value1" ng-model="val1" style="width:50px">
 <select ng-model="operation">
 <option value="A" selected>+</option>
 <option value="S">-</option>
 <option value="D">/</option>
 <option value="M">*</option>
 </select>
 <input type="text" name="Value2" ng-model="val2" style="width:50px">
 <input type="button" name="calculate" value="=" ng-click="calculate()"/>
 <input type="text" name="result" ng-model="result" style="width:50px"/>
 </div>
 </body>

</html>

script.js

(function() {

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

 var calculationController = function($scope) {

 $scope.calculate = function() {

 //Calculation logic goes here

 }

 };
 };

 app.controller("CalculationController", calculationController);

}());

Now for writing my arithmetic operation logic as a service i’ll create a new file viz. CalculationService.js.Below is the code written for the service.

 (function(){

 //calculation service implementation

 var calculationService = function()
 {
 var add = function(value1,value2){
 return parseInt(value1) + parseInt(value2);
 };
 var subtract = function(value1,value2){
 return parseInt(value1) - parseInt(value2);
 };
 var divide = function(value1,value2){
 return parseInt(value1) / parseInt(value2);
 };
 var multiply = function(value1,value2){
 return parseInt(value1) * parseInt(value2);
 };

 return {
 add : add,
 subtract : subtract,
 divide : divide,
 multiply : multiply
 };
 };

 //Get reference to the CalculationApp module

 var module = angular.module("CalculationApp");

 //Add service to the module

 module.factory("calculationService",calculationService);

 }());

Lets go one by one through important aspects of the code.


    //calculation service implementation
    var calculationService = function()
    {
     	...
	 	...
		...
	}

calculationService  is the function which defines the functionality for arithmetic operations.

    //Get reference to the CalculationApp module
      var module = angular.module("CalculationApp");

Second we get reference to our angular module viz. CalculationApp (where we have our controller logic).

    //Add service to the module
    module.factory("calculationService",calculationService);

Last step as shown above is registering our service to CalculationApp module using module.factory  method.

That’s it !!!.Our CalculationService is done.

Below is the code for using this service in our controller.

(function() {

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

 var calculationController = function($scope, calculationService) {

 $scope.calculate = function() {
 switch ($scope.operation) {
 case "A":
 $scope.result = calculationService.add($scope.val1, $scope.val2);
 break;
 case "S":
 $scope.result = calculationService.subtract($scope.val1, $scope.val2);
 break;
 case "D":
 $scope.result = calculationService.divide($scope.val1, $scope.val2);
 break;
 case "M":
 $scope.result = calculationService.multiply($scope.val1, $scope.val2);
 break;
 }

 };
 };

 app.controller("CalculationController", calculationController);

For using our service in controller (or multiple controllers) only thing we need to do is to pass calculationService  as argument to controller (i.e. a variable with same name as first string argument in module.factory method).Once you do that calculation service object will be automatically injected in the controller.

Just want to highlight that using module.factory is  just one of the ways of creating service in AngularJS.There are couple of other ways which I’ll be discussing in my future posts.

You can go through code and run the application at this location.

To further review these concepts you can go to this excellent pluralsight course on getting started with Angular JS by Scott Allen.

Tagged on: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.