Services in AngularJS Simplified With Examples

Read: 21 points cheat sheet on AngularJS controller and the $scope object

What a service is

  • It provides a method to keep data across the lifetime of the Angular app.

  • It provides a method to communicate data across the controllers in a consistent way.

  • This is a singleton object and it is instantiated only once per application.

  • It is used to organize and share data and functions across the application.

Two main execution characteristics of Angular services are that they are singleton and lazy instantiated. Angular only creates an instance of a service when an application component depends on it. On the other hand each application component dependent on the service work with the single instance of the service created by Angular.

service created by the angular

Keep in mind that services are singleton objects and are instantiated once per Angular app using the $injector and they are created when the Angular app components need them.

Let us start by creating a very simple service. This service will find the square of a given number. It is a good idea to put all the services in a separate JavaScript file. We have created the service.js file and inside that creating a service or registering a service using the service method as shown below.

  1. var CalculatorService = angular.module('CalculatorService', [])  
  2. .service('Calculator'function () {  
  3.     this.square = function (a) { return a*a};  
  4.       
  5. });  
An AngularJS service can be created or registered in one of the following four ways:  
  1. Using the service() method
  2. Using the factory() method
  3. Using the provider() method
  4. Using the value() method
  5. Using the constant() method

Further in the article we will talk about options to create the service. Above we have created the calculator service using the service() method.

To use the service in the controller, we are passing the service module CalculatorService as a dependency in the application module. Next in the controller we are passing the name of the service Calculator to be used.

  1. var myApp = angular.module('myApp', ['CalculatorService']);  
  2. myApp.controller('CalculatorController'function ($scope, Calculator) {  
  3.   
  4.     $scope.findSquare = function () {  
  5.         $scope.answer = Calculator.square($scope.number);  
  6.     }  
  7. });  
On the view we are using the controller to do the data binding as shown below:
  1. <div class="container">  
  2.         <div>  
  3.             <div ng-controller="CalculatorController">  
  4.                 Enter a number:  
  5.                 <input type="number" ng-model="number">  
  6.                 <button class="btn btn-danger" ng-click="findSquare()">Square</button>  
  7.                 <div>{{answer}}</div>  
  8.             </div>  
  9.         </div>  
  10.     </div>  
An Angular application will render as shown below:

enter name

We can create a service using the factory as shown below. We are creating the service to reverse the string.
  1. CalculatorService.factory('StringManipulation'function () {  
  2.   
  3.    var r=  function reverse(s) {  
  4.         var o = '';  
  5.         for (var i = s.length - 1; i >= 0; i--)  
  6.             o += s[i];  
  7.         return o;  
  8.     }  
  9.       
  10.    return{  
  11.        reverseString: function reverseString(name)  
  12.        {  
  13.            return r(name);  
  14.        }  
  15.    }  
  16.   
  17. });  
In the controller the StringManipulationService can be used as shown below:
  1. myApp.controller('CalculatorController'function ($scope, Calculator) {  
  2.   
  3.     $scope.findSquare = function () {  
  4.         $scope.answer = Calculator.square($scope.number);  
  5.     }  
  6. });  
On the view we are using the controller to do the data binding as shown below:
  1. <div ng-controller="StringController">  
  2.                Enter Name:  
  3.                <input ng-model="name">  
  4.                <button class="btn btn-info" ng-click="findReverse()">Reverse Name</button>  
  5.                <div>{{reversename}}</div>  
  6.            </div>  
An Angular application will render as shown below:

angular application
Let us understand the differences between creating a service using the service() method and the factory() method.  
  1. Using the service() method uses the function constructor and it returns the object or instance of the function to work with.
  2. Using the factory() method uses the returned value of the function. It returns the value of the function returned after the execution.

If we want to register a service using the function constructor then we will use the service() method to register the service. If we use the factory() method to register the service it returns the value after execution of the service function. It can return any value like primitive value, function or object. So the service() method returns the function object whereas the factory() method can return any kind of value.

In a future article we will talk about other ways of creating services. Now let us work on a full working example of using a service in an Angular app. We are going to create an application that will do the following:

  1. List students from the database.
  2. Add a student to the database.

The roughly architecture of the application can be drawn as shown below:

database

This article will not cover how to create a JSON based WCF REST Service. With the assumption that a REST based service is already in place to retrieve the students and add a student, we will write the Angular application.

The Service

  1. var StudentService = angular.module('StudentService', [])  
  2. StudentService.factory('StudentDataOp', ['$http'function ($http) {  
  3.   
  4.     var urlBase = 'http://localhost:2307/Service1.svc';  
  5.     var StudentDataOp = {};  
  6.   
  7.     StudentDataOp.getStudents = function () {  
  8.         return $http.get(urlBase+'/GetStudents');  
  9.     };  
  10.   
  11.     StudentDataOp.addStudent = function (stud) {  
  12.         return $http.post(urlBase + '/AddStudent', stud);  
  13.     };  
  14.     return StudentDataOp;  
  15.   
  16. }]);  
We are creating the service using the factory(). There are two methods in the service. getStudents fetches all the students using the $http.get whereas addStudent adds a student using the $http.post. In the service we are using other builtin Angular service $http to make the call to the service. To use the $http service, we need to pass this as a dependency to the service factory() method.

Now that the service is created, let us create the controller that will use the service to perform the operations.

The Controller
  1. var myApp = angular.module('myApp', ['StudentService']);  
  2.   
  3. myApp.controller('StudentController'function ($scope, StudentDataOp) {  
  4.     $scope.status;  
  5.     $scope.students;  
  6.     getStudents();  
  7.   
  8.     function getStudents() {  
  9.         StudentDataOp.getStudents()  
  10.             .success(function (studs) {  
  11.                 $scope.students = studs;  
  12.             })  
  13.             .error(function (error) {  
  14.                 $scope.status = 'Unable to load customer data: ' + error.message;  
  15.             });  
  16.     }  
  17.   
  18.     $scope.addStudent = function () {  
  19.           
  20.         var stud = {  
  21.             ID: 145,  
  22.             FirstName: $scope.fname,  
  23.             LastName: $scope.lname  
  24.         };  
  25.         StudentDataOp.addStudent(stud)  
  26.             .success(function () {  
  27.                 $scope.status = 'Inserted Student! Refreshing Student list.';  
  28.                 $scope.students.push(stud);  
  29.             }).  
  30.             error(function (error) {  
  31.                 $scope.status = 'Unable to insert Student: ' + error.message;  
  32.             });  
  33.     };  
  34. });  
In the controller we are adding getStudents and addStudents functions to the scope. It is clear from the name that these functions are used to fetch students and add students respectively. Since a dependency StudentSevice module is passed in the module and in the controller we are passing the StudentDataOp service as the dependency.

Another important thing to notice is that we are creating a student object to be added using the $scope object properties like fname and lname. These properties are set to the $scope on the view.

The View

The View is very simple. StudentController is attached to the view. There are two sections in the view. In the first section we are taking user input to create the student. In the second section, in a table all the students are listed.
  1. <div ng-controller="StudentController">  
  2.             <form class="well">                 
  3.                 <input type="text" name="fname" ng-model="fname" placeholder="first name" /> <br/>         
  4.                 <input type="text" name="lname" ng-model="lname" placeholder="last name" />               
  5.                 <br /><br/>                 
  6.                 <input type="button" value="add student" ng-click="addStudent()" class="btn btn-primary" />  
  7.             </form>  
  8.             <br/>  
  9.             <table class="table">  
  10.                 <tr ng-repeat="s in students">  
  11.                     <td>{{ s.FirstName }}</td>  
  12.                     <td>{{ s.LastName }}</td>  
  13.                     <td>  
  14.                         <a href="#" class="btn btn-info" ng-click="edit(contact.id)">edit</a>  
  15.                         <a href="#" class="btn btn-danger" ng-click="delete(contact.id)">delete</a>  
  16.                     </td>  
  17.                 </tr>  
  18.             </table>  
  19.         </div>  
In the input form we are setting fname and lname properties on the $scope object and then calling the addStudent() function of the controller to add a student to the database.

In the table using the ng-repeat directive all the students are listed. We have used two buttons for edit and delete. These buttons are not performing any task as of yet. In further articles we will add edit, delete and search functionality.

If you are following along the articles, you might want this functionality of your own and share your experience with me.

On running the application, you will get a form to add a student and all students listed in the table.

add a student

This is how you can create and use an angularJS service in an application. I hope you find this article useful. Thanks for reading. Happy coding.

 

Up Next
    Ebook Download
    View all
    Learn
    View all