Friday, 12 June 2015

Services Concept

Let discuss about Angular JS Services in details.

AngularJS supports the concepts of "Seperation of Concerns" using services architecture. Services are javascript functions and are responsible to do a specific tasks only. This makes them an individual entity which is maintainable and testable.

Controllers, filters can call them as on requirement basis. Services are normally injected using dependency injection mechanism of AngularJS.

Each service is responsible for a specific task, i.e.,  $http is used to make ajax call to get the server data. $route is used to define the routing information and so on. Inbuild services are always prefixed with $ symbol. There are two ways to create a service:-

  • factory
  • service

Let me elaborate Angular JS Service with a suitable example.


main.html:-
<html>
<head>
<title>Angular JS Services</title>
<script src="angular.min.js"></script>
</head>
<body>
<h2>AngularJS Services Application</h2>
<div ng-app="mainApp" ng-controller="CalcController">
<p>Enter a number: <input type="number" ng-model="number" />
<button ng-click="square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
<script src="app.js"></script>
<script src="factory.js"></script>
<script src="service.js"></script>
<script src="controller.js"></script>
</body>
</html>


app.js:-
var mainApp = angular.module("mainApp", []);


controller.js:-
mainApp.controller('CalcController', function($scope, CalcService) {
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});


service.js:-
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
}
});


factory.js:-
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});



Screenshots:-





Explanation:-

Using factory method, I first define a factory and then assign method to it. Using service method, we define a service and then assign method to it. I have also injected an already available service to it.

No comments:

Post a Comment