AngularJS - 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


   
      Angular JS Services
      
   
   
   
      

AngularJS Sample Application

Enter a number:

Result: {{result}}

Output

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

Advertisements