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>
    </div>
</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">
    <form>
    <label>Name</label> 
        <input type="text" name="name" ng-model="newcontact.name"/>
    <label>Email</label> 
        <input type="text" name="email" ng-model="newcontact.email"/>
    <label>Phone</label> 
        <input type="text" name="phone" ng-model="newcontact.phone"/>
        <br/>
        <input type="hidden" ng-model="newcontact.id" />
     <input type="button" value="Save" ng-click="saveContact()" />
    </form>
<table>
<thead> 
<tr>
    <th>Name</th>
    <th>Email</th>
    <th>Phone</th>
    <th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in contacts">
    <td>{{ contact.name }}</td>
    <td>{{ contact.email }}</td>
    <td>{{ contact.phone }}</td>
    <td>
        <a  href="#" ng-click="edit(contact.id)">edit</a> | 
        <a href="#" ng-click="delete(contact.id)">delete</a>
    </td>
 </tr>
</tbody>
</table>    
</div>

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': [email protected]',
            'phone': '123-2343-44'
    }];
    
    //save method create a new contact if not already exists
    //else update the existing object
    this.save = function (contact) {
        if (contact.id == null) {
            //if this is new contact, add it in contacts array
            contact.id = uid++;
            contacts.push(contact);
        } else {
            //for existing contact, find this contact using id
            //and update it.
            for (i in contacts) {
                if (contacts[i].id == contact.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 () {
        ContactService.save($scope.newcontact);
        $scope.newcontact = {};
    }


    $scope.delete = function (id) {

        ContactService.delete(id);
        if ($scope.newcontact.id == 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.

References

Get our Articles via Email. Enter your email address.

You may also like...

150 Comments

  1. Vicky says:

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

  2. 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 says:

      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 says:

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

  3. Joe Andrieu says:

    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" />
    

    and

    $scope.saveContact = function (newContact) {
            ContactService.save(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 says:

      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" />
      
      • Ravinder Kumar says:

        I personally consider it a good practice to write minimal code in HTML that’s why I support his approach.

  4. Nikhil says:

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

  5. Krish says:

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

  6. Thirumal says:

    Hi dude this is excellent example.
    HATS of U.

  7. Ichabodcole says:

    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).

  8. Nizar Blond says:

    Thank you for the awesome tutorial!

  9. Suma says:

    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 says:

      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!

  10. ang says:

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

  11. John Smith says:

    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.

  12. Mark Bostleman says:

    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 says:

      great tutorial…Thanks.

    • Rodney Barbati says:

      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.

  13. Rajasekhar says:

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

  14. Sagar says:

    Nice Article Viral. Keep Posting. Thanks a lot.

  15. Faizan Mustansar says:

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

    GREAT JOB… Mr.VIRUS

  16. Chris says:

    Nice tutorial. Thanks for your time

  17. UserA says:

    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!

  18. William says:

    ” 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.

  19. Tarak says:

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

  20. Hari says:

    Nice Tutorial

  21. Tom Kennedy says:

    Excellent Tutorial. Very Simple.

  22. Mayank Gupta says:

    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

  23. Paul Freeman says:

    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.

  24. Sandeep Pal says:

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

  25. Sandeep Pal says:

    Nice Tutorial. Thanks 4 the simplicity

  26. Brad says:

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

    [if (contact.id == null)]

    Any ideas?

    • Kyle says:

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

      • Dan says:

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

  27. Maheshwar says:

    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 says:

      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.

  28. Vijay says:

    Viral its really nice article for angular js

  29. Jim says:

    Hi,
    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…)

    Thanks.

  30. Umadevi says:

    Very Useful

  31. sumit maity says:

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

  32. Mark Collins says:

    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.

  33. Dmitri Shchurov says:

    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 )

  34. Saurabh Mahajan says:

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

  35. Saurabh Mahajan says:

    hi viral can u please let me know . In last example how $scope.contact 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..

  36. Dan says:

    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.

  37. Krishnaprasad says:

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

  38. Krishnaprasad says:

    Really nice post. Got a very good introduction to services

  39. Anand says:

    Excellent!! Very useful, Thanks

  40. Pradeep Tanugula says:

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

  41. saravanan says:

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

  42. Monark says:

    //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
    http://errors.angularjs.org/1.2.17/$injector/unpr?p0=IntegrityAuthServiceProvider%20%3C-%20IntegrityAuthService

    what could be its cause

  43. Mahfuz Ahmed says:

    Welcome to Spectrum Engineering Consortium LTD

    Name

    Email

    Phone

    Age

    Name
    Email
    Phone
    Age

    Action

    {{ contact.name }}
    {{ contact.email }}
    {{ contact.phone }}
    {{ contact.age }}

    edit |
    delete

    function myFunction() {
    document.getElementById(val=””);
    alert(“Shuld not be blank”);
    }

    var uid = 1;

    function ContactController($scope) {

    $scope.contacts = [
    { id:0, ‘name’: ‘Viral’,
    ’email’:’[email protected]’,
    ‘phone’: ‘123-2343-44′,’age’:’20’
    }
    ];

    $scope.saveContact = function() {

    if($scope.newcontact.id == null) {
    //if this is new contact, add it in contacts array
    $scope.newcontact.id = uid++;
    $scope.contacts.push($scope.newcontact);
    } else {
    //for existing contact, find this contact using id
    //and update it.
    for(i in $scope.contacts) {
    if($scope.contacts[i].id == $scope.newcontact.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.contacts.splice(i,1);
    $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 !

  44. giriswamy says:

    Wow super article

  45. Durga says:

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

  46. Nilima says:

    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.
    Thanks

  47. simonced says:

    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 says:

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

  48. Rajasekar says:

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

  49. Amarnath says:

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

    • Amarnath says:

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

  50. swaroop says:

    it is very difficult understand for the people who starts beginners

  51. A.Lepe says:

    Your tutorials on AngularJS helped me to startup with it (looking forward for more of this serie!). I wish they were included on the AngularJs website as they are very clear and easy to follow. Thanks!

  52. Amruth says:

    Thanks Buddy for the great tutorial, it was very helpful for beginner like me.You have pointed the things in a very understandable manner.

  53. trendrumah says:

    it helped me, understandable
    Thanks

  54. JSolo says:

    Wonderful stuff! Was able to connect to SQL server db via express.js to serve up nice rest api and get some nice UI going

    Thanks so much!!!

  55. Anup kumar says:

    I am also trying to call a method of one service into the other service but it is giving error saying
    Cannot read property ‘create’ of undefined

    app.service('CookieService', ['$cookies',
        function ($cookies) {
            this.create = function (token, userName) {
                $cookies.token = token;
                $cookies.name = userName;
            };
            return this;
    }]);
    
    app.service('AuthService',
        function (CookieService) {
            return {
                login: function (credentials) {
                         CookieService.create(token,username);
    }
    };
    });
    

    Please ignore syntax error if it is there

  56. Al says:

    We needed an example of using a factory. Please work on your english. Thanks.

  57. Syed Shaik shavali says:

    Thanks..Good article.

  58. Jason Maggard says:

    Thanks a million. Very well explained and easy to follow. Very much appreciated.

  59. Ankit says:

    Well explained article ,thanks a lot for your blog.

  60. rick says:

    Great example Viral, (and your English is just fine). Thank you.

  61. Martin says:

    One of the best tutorials I have used in a long time. Well done. Perhaps a little more info on pros and cons of factory\service approaches.

  62. Haresh says:

    After seeing your tutorial I can started with AngularJS Project. THANKS………..

  63. evans says:

    it was very helpful. thanks

  64. Tuan Nguyen says:

    Thanks so much! I can see how service and factory work and how they connect with controller

  65. Nishant says:

    Thanks for the tutorial..
    the simplified way in which you explained the concepts is commendable

  66. Very good Example and Easy to Under stand for Every one. Thanks Lot

  67. anil says:

    is there any way to create multiple instances of a factory in another factory ?
    //factory 1
    module.factory(‘MyService’, function() {

    });

    //factory2
    module.factory(‘MyService1’, [ ‘MyService’ , function( MyService) {
    var obj = new MyService();
    }]);

  68. anil says:

    is there any way to create multiple instances of a factory in another factory ?
    //factory 1
    module.factory(‘MyService’, function() {
    });
    //factory2
    module.factory(‘MyService1′, [ ‘MyService’ , function( MyService) {
    var obj = new MyService();
    }]);

  69. William says:

    This was an incredibly well-written and informative tutorial. Thanks for sharing your wealth of knowledge. This really clarified things for me. Cheers again!

  70. Sumanth says:

    Thank you so much. This article helped me a lot in understanding AngularJS. This is very easy to follow.

  71. Palak says:

    Awesome article !!

  72. Balachandar says:

    Welldone…Excellent Explanation…Keep the good work…

  73. channu yatnur says:

    Thank you very much….great tutorial

  74. Arun says:

    nice article

  75. Derek says:

    Excellent tutorial. This is very clear and the example using the service approach works nicely! Thanks for posting it. You should help on the next O’Reilly Angular book. They could use it :-)

  76. jdawg says:

    Section one, last sentence, “Thus our application becomes for modular and testable.” I think you meant to write more, not for.

    Thanks,

    Grammar Guy

  77. jdawg says:

    Section one, third paragraph, first sentence. “Thus service is a stateless object that contains some useful functions.” I think you meant to write The, not Thus…

  78. Abu Noman says:

    Nice tutorial, Good job…… Thnx

  79. Thank you. It’s easy to follow.

  80. rohini says:

    Very good tutorial really even for beginners also it’s very easy to understand not only this post for Java, JQuery,spring i am getting good knowledge from this site….Thank you so much viral

  81. Himali says:

    Its great tutorial for beginner!!! Thank you a lot!!!

  82. Adonis says:

    Thanks a lot, this was very informative about controllers and services. Well done.

  83. Chandra Shelar says:

    Very simple way to explain. I cleared my concepts using your articles & examples.
    Can you please add custom directive tutorial?

    Thnx
    Chandra

  84. Great article, much easier to follow than a lot on the web – at last an article that KISS!

  85. A says:

    This was lucid. Thanks for taking time to write this.

  86. Sandy says:

    Thanks Viral, for the excellent tutorial, it’s very easy to understand & to practice the tutorials these were really helpful, waiting to see the new interesting topics on Angular JS.

    Thanks,
    Sandeep.

  87. Modela Satyam says:

    Thanks Viral, excellent tutorial, nice flow, easy to understand.

  88. NaveenKumar says:

    Awesome tutorial with examples, even a biginners can follow these and get into knowledge of subject easily.
    Thanks a lot

  89. Chiranjeevi says:

    Thanks Viral, Please send a post on AngularJS with RESTful web services.

  90. Huy says:

    An excellent tutorial. Thank you so much. By the way, could you please tell me whether it can read a json from an URL instead of directly initialize in the service.js file? (For example, you have written //contacts array to hold list of all contacts
    var contacts = [{
    id: 0,
    ‘name’: ‘Viral’,
    ’email’: ‘[email protected]’,
    ‘phone’: ‘123-2343-44’
    }];
    and I want to read dynamic data from an URL)
    Thanks.

  91. ahmet says:

    Thanks this blogentry.I understood how to be use service , controller together .. thank you again

  92. Meesam Zaidi says:

    Nice job buddie, Thanks a lot.

  93. Ofir Aghai says:

    nice guide,
    But you dont explain much on the main question, when should i use Service, and when we should Factory

  94. Arjun says:

    Nice explanation of service and factory I was struggling a lot now you made me clear. Thank you so much………. :)

  95. Bhavuk says:

    Clearrd many doubts regarding angular.
    Thanks buddy (y)

  96. Amit Kumar Dubey says:

    This is classic, you explained with serenity .
    Thanks Guru!

  97. bs says:

    Good article. One thing not clear to me that when to use service and when to use factory?

  98. Binh Thanh Nguyen says:

    Thanks, nice post

  99. very nice for angularjs learner
    thank you very much
    please help me how to create controller and service in project
    if i have more than one function at the time like save , edit , dropdown , then how to define service in service page
    please help me

    i am learner for angularjs
    i hope , you help me soon

  100. Arpit says:

    Many thanks brother.

  101. marco says:

    thank you a lot, very to the point, no fuss and effective tutorial.

  102. Vishal says:

    Really Awesome Article.. Patel Bhai….I have started learning Angular.. ..Good One..

  103. SAURAV says:

    Please……………..
    create a tutorial on node.js.
    I am impressed with your tutorial

  104. Hari Mutyala says:

    Very nicely explained.. i got a clear picture of services . With you permission i would like to answer the question most of them asking .
    Factory vs Service : If we need an object in return use Factory … if we need a function or object use Service .

    Please correct me if i am wrong.

  105. stav says:

    thanks so much. was great article!! waiting for more!

  106. Sourabh says:

    Great Tutorial thank for the help in understanding AugularJS.

  107. yatendra says:

    It is nice article, very useful for beginners…..

  108. Danny Fardy Jhonston Bermúdez says:

    Very useful. Thank you.

  109. Vitthal says:

    Thank you very much, this blog help me to clearly understand angular js. Realy nice blog

  110. rav says:

    nice tutorial ..thank you

  111. Vivvv says:

    I don’t understand exactly how contacts-variable in the scope get updated? When I save something it pushes the new object to service’s contacts array but how these changes are updated in $scope?

    • Raham says:

      Dear Vivvv!

      First please check the html form’s hidden id and then keep focus on save function.It has a very clear logic.

  112. Ramesh Khanna says:

    Good One.

  113. Mohamed says:

    ViralPatel – I really appreciate you for having given clear explanations with neat examples and code. I have never seen it in any other sites. Please continue the great job – your examples are great and works perfect

  114. alePanta says:

    Thanks, very clear!

  115. Thank you very much! Great tutorial!

  116. sam says:

    hello world

  117. Lateef says:

    God bless You. This tutorial rocks.

  118. Mihir says:

    This is really helpful. Clean and very easy to understand. Thanks a ton…… :)

  119. Raham says:

    Really Awesome Article…
    Great…

  120. Joydeep says:

    Thanks. A concrete tutorial. Just to the point

  121. Tom M. says:

    Very impressive tutorial – absolutely to the point with real world application, well done!!

  122. vikram says:

    Its what the actual post. I got to work with services now. Thanks.

  123. Rajeev Singh says:

    Hello,

    Really nice article I have a question,
    Can service object be injected in multiple controller’s spread across many different .js files and be used to call service methods for calculations ?????? I tried actually and failed to do so, thats why asking.

  124. devy says:

    Its really good. Thanks for your article. Please update services using $resource

  125. Debasmit says:

    This is excellent. It is very clear to understand what is service and what is factory with simple examples. I appreciate.

  126. Carol says:

    Thank you . Great article

  127. Pradeep says:

    Excellent Article. Nicely written and well explained. Thanks.!

  128. Sumit Arora says:

    Excellent and the great and then great and very great and super great article ! It clearly defines the differnence between Service and Factory, and easy way to understand AngularJs.

  129. Natarajan says:

    This is a great article for a beginner like me. But I have one question. What if the SAVE button is changed to SUBMIT button. The reason being I can also enter filter information in the top portion of the form that should in essence restrict the list portion at the bottom. Can u please explain how we do this. This would be of great help.

    Thanks

  130. Natarajan says:

    Also I forgot to mention. How to link this to the back end REST service that provides data. How to transfer the search data back to the client side?

  131. vijay says:

    Excellent

  132. Ravinder Kumar says:

    Nice job!

  133. RohitSG says:

    Really this one is a clear stuff.

  134. Brianmanden says:

    Great tutorials! I enjoyed reading them.

    Thank you :)

  135. Geoff says:

    Perfect. Simple and clear.

  136. Ishtiaq says:

    Thanks bro

  137. RITURAJ RATAN says:

    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.

    can you make it little bit simple it is same like http://stackoverflow.com/questions/15666048/angularjs-service-vs-provider-vs-factory

Leave a Reply

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