AngularJS Services - Simple Example

Welcome to PART 4 of AngularJS tutorial series and we are going to see in detail, one of the important aspect of AngularJS, "The AngularJS Services". Before reading this article, it is recommended to look at my previous articles on AngularJS for understanding the basics.

You might have heard about this term "Services" in server side programming. Now, in a client side library like AngularJS what this means is wrapping up some functionality that can be injected in all of your controllers, directives, filters and other services as well. 

So far, in my previous articles we used controllers for everything such as gluing model and view, provide some functionality, etc. This is not the right approach to proceed. Especially when we use javascript libraries like AngularJS to do client side mvc, it is very important to follow 'separation of concerns' design principle. Every feature should have a single responsibility, for example controllers are meant for attaching model with the view via scope object and other business logic should be placed somewhere else which could then be injected/used whenever they are needed. This is the purpose why we have services in AngularJS.

Services can be created and used to implement specific tasks such as fetching data from server via AJAX calls or do some other calculations. AngularJS also provides a set of built-in services which we will explore later in this tutorial series. Let us start by creating a custom service with a simple functionality and injecting it to a controller. 

Let us take the same scenario, which I used to explain controllers in AngularJS. We used controllers to calculate the total price for the corresponding quantity entered and bind the result to view. The controller in that example looked like this,

myFirstModule.controller('myFirstController', function($scope) {
 $scope.calculate = function(xval,yval) {                       

Let us introduce services here to perform calculate function. You can create a service in four different ways, but let us create one by registering a service with the factory method in the module api. To learn about other ways of creating service take a look at this article. To create a service, you must first define a module for your application to which this service belongs and then register it to the module using factory method of the module api as shown below,

myModule.factory('serviceName', function() {
    return { };

Let us now recreate our controller example for performing total price calculation using services.

<!DOCTYPE html>
<html ng-app="myAppModule">
<title>Angular JS -</title>
<link href="" rel="stylesheet" type="text/css" />
<script type="text/javascript"
<div ng-controller="myAppController" style="text-align:center">
     <p style="font-size:28px;">Enter Quantity:
 <input type="text" ng-model="quantity"/></p>
 <h2>Total Cost: Rs.{{calculateval(quantity,10)}}</h2>
<script type="text/javascript">
 var myAppModule = angular.module('myAppModule', []);
    myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.calculateval = function(xval,yval) {                       
   return calculateService.calculate(xval,yval);
// Service 
 myAppModule.factory('calculateService', function(){
    return {
        calculate: function(xval,yval){
            return xval*yval;

If you note in the above example, the functionality for calculating total price for the given quantity is performed in a service called, 'calculateService' and it is injected in controller to be called every time when value in the text box changes (quantity). Since we have bound 'quantity' as model to text input, total cost will automatically update whenever the value of 'quantity' model changes. AngularJS adds a $watch attribute behind the scenes, that keeps tracking the changes in the model and whenever the value changes all attributes using that model will be updated automatically. Here the controller depends on the service for performing calculation and does its actual job of binding calculation results to the view.

That is all for now! We have created a simple custom service and injected in a controller successfully. In my next article, I will show you how to use $http service to fire ajax calls and communicate with the server.

Please keep yourself subscribed and get notified whenever a new article is published. Thanks for reading!! 



AngularJS 7979587216076714292

Post a Comment