AngularJS Service / Factory Tutorial with Example

angularjs service

1. Introduction to AngularJS Services

In AngularJS world, the services are singleton objects or functions that carry out specific tasks. It holds some business logic. Separation of concern is at the heart while designing an AngularJS application. Your controller must be responsible for binding model data to views using $scope. It does not contain logic to fetch the data or manipulating it.

For that we must create singleton objects called services. AngularJS can manage these service objects. Wherever we want to use the service, we just have to specify its name and AngularJS auto-magically inject these objects (more on this later).

Thus service is a stateless object that contains some useful functions. These functions can be called from anywhere; Controllers, Directive, Filters etc. Thus we can divide our application in logical units. The business logic or logic to call HTTP url to fetch data from server can be put within a service object.

Putting business and other logic within services has many advantages. First it fulfills the principle of separation of concern or segregation of duties. Each component is responsible for its own work making application more manageable. Second this way each component can be more testable. AngularJS provides first class support for unit testing. Thus we can quickly write tests for our services making them robust and less error prone.

angularjs service diagram

Consider above diagram. Here we divide our application in two controllers: 1. Profile and 2. Dashboard. Each of these controllers require certain user data from server. Thus instead of repeating the logic to fetch data from server in each controller, we create a User service which hides the complexity. AngularJS automatically inject User service in both Profile and Dashboard controller. Thus our application becomes for modular and testable.

2. AngularJS internal services

AngularJS internally provides many services that we can use in our application. $http is one example (Note: All angularjs internal services starts with $ sign). There are other useful services such as $route, $window, $location etc.

These services can be used within any Controller by just declaring them as dependencies. For example:

module.controller('FooController', function($http){

module.controller('BarController', function($window){

3. AngularJS custom services

We can define our own custom services in angular js app and use them wherever required.

There are several ways to declare angularjs service within application. Following are two simple ways:

var module = angular.module('myapp', []);

module.service('userService', function(){
	this.users = ['John', 'James', 'Jake'];

or we can use factory method

module.factory('userService', function(){
	var fac = {};
	fac.users = ['John', 'James', 'Jake']; 
	return fac;


Both of the ways of defining a service function/object are valid. We will shortly see the difference between factory() and service() method. For now just keep in mind that both these apis defines a singleton service object that can be used within any controller, filter, directive etc.

4. AngularJS Service vs Factory

AngularJS services as already seen earlier are singleton objects. These objects are application wide. Thus a service object once created can be used within any other services or controllers etc.

We saw there are two ways (actually four, but for sake of simplicity lets focus on 2 ways that are widely used) of defining an angularjs service. Using module.factory and module.service.

module.service( 'serviceName', function );

module.factory( 'factoryName', function );

When declaring serviceName as an injectable argument you will be provided with an instance of the function. In other words new FunctionYouPassedToService(). This object instance becomes the service object that AngularJS registers and injects later to other services / controllers if required.

When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

In below example we define MyService in two different ways. Note how in .service we create service methods using this.methodname. In .factory we created a factory object and assigned the methods to it.

AngularJS .service

module.service('MyService', function() {
	this.method1 = function() {

	this.method2 = function() {

AngularJS .factory

module.factory('MyService', function() {
	var factory = {}; 

	factory.method1 = function() {

	factory.method2 = function() {

	return factory;

5. Injecting dependencies in services

Angularjs provides out of the box support for dependency management.

In general the wikipedia definition of dependency injection is:

Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time. …

We already saw in previous tutorials how to use angularjs dependency management and inject dependencies in controllers. We injected $scope object in our controller class.

Dependency injection mainly reduces the tight coupling of code and create modular code that is more maintainable and testable. AngularJS services are the objects that can be injected in any other Angular construct (like controller, filter, directive etc). You can define a service which does certain tasks and inject it wherever you want. In that way you are sure your tested service code works without any glitch.

Like it is possible to inject service object into other angular constructs, you can also inject other objects into service object. One service might be dependence on another.

Let us consider an example where we use dependency injection between different services and controller. For this demo let us create a small calculator app that does two things: squares and cubes. We will create following entities in AngularJS:

  1. MathService – A simple custom angular service that has 4 methods: add, subtract, multiply and divide. We will only use multiply in our example.
  2. CalculatorService – A simple custom angular service that has 2 methods: square and cube. This service has dependency on MathService and it uses MathService.multiply method to do its work.
  3. CalculatorController – This is a simple controller that handler user interactions. For UI we have one textbox to take a number from user and two buttons; one to square another to multiply.

Below is the code:

5.1 The HTML

<div ng-app="app">
    <div ng-controller="CalculatorController">
        Enter a number:
        <input type="number" ng-model="number" />
        <button ng-click="doSquare()">X<sup>2</sup></button>
        <button ng-click="doCube()">X<sup>3</sup></button>
        <div>Answer: {{answer}}</div>

5.2 The JavaScript

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

app.service('MathService', function() {
    this.add = function(a, b) { return a + b };
    this.subtract = function(a, b) { return a - b };
    this.multiply = function(a, b) { return a * b };
    this.divide = function(a, b) { return a / b };

app.service('CalculatorService', function(MathService){
    this.square = function(a) { return MathService.multiply(a,a); };
    this.cube = function(a) { return MathService.multiply(a, MathService.multiply(a,a)); };


app.controller('CalculatorController', function($scope, CalculatorService) {

    $scope.doSquare = function() {
        $scope.answer = CalculatorService.square($scope.number);

    $scope.doCube = function() {
        $scope.answer = CalculatorService.cube($scope.number);

5.3 Online Demo

Thus in the above angularjs injected service object to another service and in turn injected final service object to the controller object. You can inject same service object in multiple controllers. As angularjs service object is inheritedly singleton. Thus only one service object will be created per application.

6. End to End application using AngularJS Service

Let us apply the knowledge that we acquired so far and create a ContactManager application. This is the same app that we built-in our last tutorial. We will add a service to it and see how we can divide the code between service and controllers. Following are some basic requirements of this application:

  1. User can add new contact (name, email address and phone number)
  2. List of contacts should be shown
  3. User can delete any contact from contact list
  4. User can edit any contact from contact list

Following is the HTML code which defines a FORM to save new contact and edit contact. And also it defines a table where contacts can be viewed.

6.1 The HTML

<div ng-controller="ContactController">
        <input type="text" name="name" ng-model=""/>
        <input type="text" name="email" ng-model=""/>
        <input type="text" name="phone" ng-model=""/>
        <input type="hidden" ng-model="" />
     <input type="button" value="Save" ng-click="saveContact()" />
<tr ng-repeat="contact in contacts">
    <td>{{ }}</td>
    <td>{{ }}</td>
    <td>{{ }}</td>
        <a  href="#" ng-click="edit(">edit</a> | 
        <a href="#" ng-click="delete(">delete</a>

Next we add the AngularJS code to and life to our ContactManager appllication. We define a module ‘app’. This module is then used to create Service and Controller.

See in below code how ContactService is created. It has simple methods to save/delete/get the contact.

Note how the service object in injected in controller.

6.2 The JavaScript

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

module.service('ContactService', function () {
    //to create unique contact id
    var uid = 1;
    //contacts array to hold list of all contacts
    var contacts = [{
        id: 0,
        'name': 'Viral',
            'email': '',
            'phone': '123-2343-44'
    //save method create a new contact if not already exists
    //else update the existing object = function (contact) {
        if ( == null) {
            //if this is new contact, add it in contacts array
   = uid++;
        } else {
            //for existing contact, find this contact using id
            //and update it.
            for (i in contacts) {
                if (contacts[i].id == {
                    contacts[i] = contact;


    //simply search contacts list for given id
    //and returns the contact object if found
    this.get = function (id) {
        for (i in contacts) {
            if (contacts[i].id == id) {
                return contacts[i];

    //iterate through contacts list and delete 
    //contact if found
    this.delete = function (id) {
        for (i in contacts) {
            if (contacts[i].id == id) {
                contacts.splice(i, 1);

    //simply returns the contacts list
    this.list = function () {
        return contacts;

module.controller('ContactController', function ($scope, ContactService) {

    $scope.contacts = ContactService.list();

    $scope.saveContact = function () {$scope.newcontact);
        $scope.newcontact = {};

    $scope.delete = function (id) {

        if ($ == id) $scope.newcontact = {};

    $scope.edit = function (id) {
        $scope.newcontact = angular.copy(ContactService.get(id));

6.3 Online Demo

That’s All Folks

We saw that angularjs service/factory objects are. How to define our own custom service/factory object in angularjs. Also we saw how dependency injection works. In the end we created a simply calculator application that wrap up all the concepts.

I hope you liked this tutorial. Feel free to post your comment below.

In this ongoing series, I will try to publish more AngularJS articles on topics like angularjs $http service, AngularJS filters, AngularJS directives etc.



  • Vicky 8 January, 2014, 21:01

    Some great articles you have posted! Any article that you can refer to display grid with AngularJS service? Thanks!

  • Zeeshan Akhter 10 January, 2014, 23:01

    Hi that is great quick start tutorial for AngularJS
    but tell me how i use that AngularJS to persist data in db
    and also tell me how you secure business logic from user side in AngularJS

    • vj 13 January, 2014, 2:07

      Sorry you cant. This is a client side app framework. Only things which are not too sensitive must be coded in angular. You have the rest of the logic in the server side.
      Client side code can always be viewed in the devtools.
      But you can still make it really tough to understand for the person looking at your code by obfuscating it. Thats all I know!

    • siddharth 6 May, 2014, 11:56

      Why dont you use HTML5’s Local storage or the webSQL. Both are great.

  • Joe Andrieu 24 January, 2014, 12:05

    Is there any particular reason not to pass the newcontact directly from the ng-click as a parameter of save()?

    <input type="button" value="Save" ng-click="saveContact(newcontact)" class="btn btn-primary" />


        $scope.saveContact = function (newContact) {

    This seems to me to have better reusability and encapsulation. For example, you may want to be able to add a new contact from somewhere else without binding to the single input you already have.

    Anyway, I am honestly curious if there is any particular “Angular” reason to do it the way you did.

    • Joe Andrieu 24 January, 2014, 12:08

      Also, I realize you clear the $scope.newcontact var after saving… if you use the variation I suggested, you can still do that in the ng-click:

      <input type="button" value="Save" ng-click="saveContact(newcontact);newcontact={};" class="btn btn-primary" />
  • Nikhil 24 January, 2014, 12:51

    This is a great tutorial to start with anulgar’s service & factory…
    Thanks a lot for giving a sweet & small expample…

  • Krish 10 February, 2014, 5:36

    Hi Viral, Have been following your tutorials on AngularJS. The explanation is very crisp and clear. Please keep posting more tutorials in the future.

  • Thirumal 24 February, 2014, 23:41

    Hi dude this is excellent example.
    HATS of U.

  • Ichabodcole 1 March, 2014, 6:43

    Thank you for making the tutorial.
    One thing that seems to be missing, and was in fact the reason I read the tutorial, was an answer to the question of when to use a factory vs a service? Can you provide different use cases for when one would be preferable over the other? Seems like a factory could just as easily return a function, which would make it identical to a service (Is this correct).

  • Nizar Blond 3 March, 2014, 16:36

    Thank you for the awesome tutorial!

  • Suma 6 March, 2014, 0:06

    Hi Viral,

    I am newbie to AngularJS and this article has helped me a lot in understanding concepts.

    I am trying to code something like :- I have a dropdown and when I select one value, it should in turn open another drop down and if not, the second dropdown should not be displayed.

    For ex. I have dropdown with values A, B, C and when I select C, I should see another select element with values in it. But when I select A or B, the second select is not visible. How can I achieve this?

    Thanks in advance.

    • Rodney Barbati 20 July, 2014, 20:48

      You should look at ng-if, ng-show and ng-hide.

      These will allow you to control whether or not the second selection box displays by setting an expression on it, as follows…

      ng-if will add the element to the dom model if the condition is true. This means if the expression is false, the element does not even exist, so be careful if referencing it from elsewhere.
      ng-show will show the element only if the condition is true, hide when false. The element will always exist in the DOM.
      ng-hide is the exact reverse of show. Shows when the expression is false, hide when true.

      Happy Coding!

  • ang 6 March, 2014, 15:44

    can you please post an example on using multiple filters with multiple input text boxes in angularjs

  • John Smith 14 March, 2014, 23:04

    Yay, another over simplified tutorial that ignores the complexity of any real-world app. Try doing this example when the model data is requested asynchronously from the server. Then add another controller that needs to share data using the service. That would be a very simple and practical example, however the code required to achieve that is way more complex than you would imagine. And you could take it one step further, how about instead of having a save button like you would on a web page from 10 years ago, you handle data automatically being updated when an input changes.

    I’m sorry, but I’ve been through a hundred tutorials just like this. Afterwards I feel like I can jump right in and create a simple app, until I add one more controller and deal with real data from a server, then all the sudden everything in these tutorials is irrelevant. Tutorials titled “Sharing data between controllers using services” will have an example with static data, one service, and one controller. Yes, I know you can create a service and inject that service into all of your controllers, but so what? That’s the least of the problems with sharing data between controllers. The real issue is how do you keep your data in sync between all of your services and controllers and the server, and what is the best way to handle the asynchronous nature of loading data into the application. Those are the practical real world scenarios that tutorials need to explain.

  • Mark Bostleman 19 March, 2014, 1:11

    John Smith – you seem like the smartest guy in the room. You should stop reading so many dumb tutorials and start writing good ones.

    Viral (or anyone) – One thing I don’t understand is where $scope.newcontact is declared or exposed on the controller? It’s used in the 3 functions on the controller – but it is not actually on the controller itself anywhere. Is this an oversight or am I missing something?

    • shafaat 29 May, 2014, 18:43

      great tutorial…Thanks.

    • Rodney Barbati 20 July, 2014, 21:27

      The newContact value is created in the $scope.edit(id) function defined in the controller. It is called when the user clicks the edit button on a particular contact. It is also created in the save() method, but only after the save has completed. It is also created in the delete method if the id in the newContact matches the passed id.

      From just a brief review of the code, this looks like it could blow up for many reasons – trying to save before editing, deleting before editing.

      It would be much better to declare the $scope.newContact variable and its initial structure in the controller than to hide its creation in various methods. You could even have a function in the service return the initial structure so it could be updated in a single place later.

  • Rajasekhar 16 April, 2014, 11:20

    Excellet Viralpatel. Thanks i have learned AngularJS in just one hour with your tutorial.

  • Sagar 22 April, 2014, 19:36

    Nice Article Viral. Keep Posting. Thanks a lot.

  • Faizan Mustansar 2 May, 2014, 18:20

    This is one great tutorial… I am able to create my own Angular Service… in 15 mins…


  • Chris 12 May, 2014, 15:22

    Nice tutorial. Thanks for your time

  • UserA 14 May, 2014, 2:27

    Viral – just wanted to quickly compliment you on your articles – they are really well-done, and easy to understand. I very much appreciate the time you take to write up these AngularJS tutorials, and I hope you continue to write more of them!

  • William 20 May, 2014, 18:08

    ” You can inject same service object in multiple controllers. As angularjs service object is inheritedly singleton. Thus only one service object will be created per application.”

    THANK YOU! I couldn’t find this answer anywhere, ended up just testing it to see what happened.

  • Tarak 22 May, 2014, 11:47

    This is a excellent tutorial to start with anulgar’s service & factory…and my hart full thanx for providing such a great tutorial.

  • Hari 3 June, 2014, 10:30

    Nice Tutorial

  • Tom Kennedy 7 June, 2014, 1:37

    Excellent Tutorial. Very Simple.

  • Mayank Gupta 10 June, 2014, 16:31

    The this.add = function(a, b) { return a + b }; should be
    this.add = function(a, b) { return ( parseInt(a) + parseInt(b) ) } ..
    Because + is having concatenation property By default

  • Paul Freeman 11 June, 2014, 20:15

    I’ve been surfing different explanations of the differences between service and factory for the last hour and this is by far the clearest and best explanation for an experienced classical OO developer.

    Excellent work, it addressed my use case exactly. If I can make one suggestion, it would have been great if you had provided some unit tests to show how they can be set up.

  • Sandeep Pal 13 June, 2014, 16:40

    Thanks alot, this is really a very good tutorial for the starter/beginner’s. Hope you will continue doing the same further…

  • Sandeep Pal 13 June, 2014, 18:11

    Nice Tutorial. Thanks 4 the simplicity

  • Brad 17 June, 2014, 20:18

    I’m getting a cannot read property ‘id’ of undefined flagging on this line;

    [if ( == null)]

    Any ideas?

    • Kyle 18 June, 2014, 23:23

      Hey Brad, I am having the same issue. Let me know if you fix it. I’m going to continue working on it.

      • Dan 12 August, 2014, 0:54

        if ( == null) can just be if ( as it would be evaluated as true or false. It works in my app.

  • Maheshwar 18 June, 2014, 19:17

    hello sir, angularjs provide a two way data binding can i possible two use angularjs with servle,jsp & JDBC if u have any idea post it in ur blog thanks sir

    • Rodney Barbati 20 July, 2014, 21:12

      You definitely can not use JDBC directly. To use it from angular, create a web service on the server that performs all the database work and returns its results as JSON. You can then call this service from within an Angular application by using the angular $http service.

      The same thing goes for a servlet – since it is already on one or more URLs, you can call it from angular using the $http service.

      Best practice would have you create an angular service which encapsulates the calls to these services.

      You would then call the angular services from your angular controller and assign the results to $scope values. If you bind your UI objects to these scope values, changes to the UI controls will update the data, and vice versa. In order to save the data back to the database, use the $scope variables as parameters to the save() methods on your angular service.

      If you use spring on your server side, spring can cast the JSON data from the client into a matching java object for further processing.

  • Vijay 18 July, 2014, 18:52

    Viral its really nice article for angular js

  • Jim 22 July, 2014, 1:16

    I’ve a question related to your service definition.
    From this post: “…service is a stateless object that contains some useful functions”

    Then, in the “Custom services” section you create services like this one:

    module.service(‘userService’, function(){
    this.users = ['John', 'James', 'Jake'];

    Is the previous service stateless? (taking into account that it contains a list of users…)


  • Umadevi 22 July, 2014, 13:01

    Very Useful

  • sumit maity 22 July, 2014, 14:58

    Some great articles you have posted! Any article that you can refer to display grid with AngularJS service? Thanks!

  • Mark Collins 24 July, 2014, 4:49

    Great post. Really useful. Just a quick question, in “5. Injecting dependencies in services” why did you use services, rather than factories? Both would work, right? Just trying to understand why to use one not the other.

  • Dmitri Shchurov 30 July, 2014, 18:05

    Great post. Can you add few more words which will explain a difference between “instance of a method” that service returns and “object with assigned methods” that factory returns relatively to a real world applications? For newbies please )

  • Saurabh Mahajan 31 July, 2014, 18:46

    Excellent for beginners…Thanks a lot Viral ….Keep Posting……

  • Saurabh Mahajan 31 July, 2014, 18:52

    hi viral can u please let me know . In last example how $ is updated automatically When I push contact in service contact object. I know we bind our $scope.contacts = ContactService.list(); . I am not clear how all the time(at the time of edit, delete ,add) our main $scope.contacts is updated . Is it updated (called) all time.

    Please let me know.

    Thanks in advance. and Keep posting..

  • Dan 12 August, 2014, 0:58

    Viral, this is a nice article. A good explanation on Service vs. Factory. In your example, it would be great if you tested for success or error on the return.

  • Krishnaprasad 13 August, 2014, 23:55

    Really nice post. Got a very good introduction to services and factory

  • Krishnaprasad 13 August, 2014, 23:57

    Really nice post. Got a very good introduction to services

  • Anand 27 August, 2014, 14:46

    Excellent!! Very useful, Thanks

  • Pradeep Tanugula 10 September, 2014, 20:28

    I need a code to Add a title in the popup based on the type of the any document using angularjs.
    thanks in advance.

  • saravanan 11 September, 2014, 13:06

    Superb. Thanks For YOur Example.
    Suoerbbbbb.. This work awesome. i complete angular services . and 50% chapter….

  • Monark 16 September, 2014, 18:34

    //Service code
    var integrityService = angular.module(‘starter.IntegrityService’, []);
    integrityService.service(‘IntegrityAuthService’, [‘configData’, function($http,’serverDetails’){
    [/code javascript]

    var appController = angular.module(‘starter.controllers’, []);

    appController.controller(‘AppCtrl’,function($scope, $ionicModal, $timeout,$location,IntegrityAuthService) {
    [/code javascript]

    Getting below error
    Error: [$injector:unpr] Unknown provider: IntegrityAuthServiceProvider <- IntegrityAuthService$injector/unpr?p0=IntegrityAuthServiceProvider%20%3C-%20IntegrityAuthService

    what could be its cause

  • Mahfuz Ahmed 18 September, 2014, 17:50

    Welcome to Spectrum Engineering Consortium LTD







    {{ }}
    {{ }}
    {{ }}
    {{ contact.age }}

    edit |

    function myFunction() {
    alert(“Shuld not be blank”);

    var uid = 1;

    function ContactController($scope) {

    $scope.contacts = [
    { id:0, 'name': 'Viral',
    'phone': '123-2343-44','age':'20'

    $scope.saveContact = function() {

    if($ == null) {
    //if this is new contact, add it in contacts array
    $ = uid++;
    } else {
    //for existing contact, find this contact using id
    //and update it.
    for(i in $scope.contacts) {
    if($scope.contacts[i].id == $ {
    $scope.contacts[i] = $scope.newcontact;

    //clear the add contact form
    $scope.newcontact = {};

    $scope.delete = function(id) {

    //search contact with given id and delete it
    for(i in $scope.contacts) {
    if($scope.contacts[i].id == id) {
    $scope.newcontact = {};


    $scope.edit = function(id) {
    //search contact with given id and update it
    for(i in $scope.contacts) {
    if($scope.contacts[i].id == id) {
    //we use angular.copy() method to create
    //copy of original object
    $scope.newcontact = angular.copy($scope.contacts[i]);

    Great !

  • giriswamy 25 September, 2014, 17:51

    Wow super article

  • Durga 26 September, 2014, 18:38

    excellent article, it is very useful Us…………. Thanks a lot………………….

  • Nilima 7 October, 2014, 20:54

    Hi viral,
    Thanks for the explanation. I have a query . We are developing a web application using angular js where the menu is created based on the role of the user who logs in. Now post login this menu is going to be static and will be a part of header div. for such views also should we rely on $scope for menu data or can we add it to session storage etc. your input would really help.

  • simonced 14 October, 2014, 19:18

    Nice article, but I’m still a bit confused.
    I did a mistake in my app today, and then stumbled across your article.
    I mixed the methods and my script worked fine:

    service('practiceSetup', function() {
    	return {
    		problemCount : 10,
    		hintsByProblem: 0,
    		retriesByProblem: 0,
    		ready: false

    I wanted what you explained to be a factory, but I used “service” instead.
    I then swapped back service for factory, and everything seemed to work identically. Of course my factory is still a work in progress, but the content didn’t seem to make any difference on the controller side (simply using the reference, not instantiating the object).
    I’m not sure I understood better, but I’ll try to stick the factory “syntax” but it seems more natural to me XD.

    • simonced 14 October, 2014, 19:20

      Arg, sorry, I realised that in my last sentence, my second “but” should have been “because” XD

  • Rajasekar 17 October, 2014, 11:54

    Excellent work . Keep it up…God bless you for all your efforts in helping others learning the technology….

  • Amarnath 18 October, 2014, 14:33

    Thanks for the article. But can you please explain how do we do the same Calculator app using factory?

    • Amarnath 18 October, 2014, 14:50

      Thanks. I am able to do the same using factory.

Leave a Reply

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


To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *