Blogger news

Blogger templates

Thursday, July 24, 2014

Service vs Factory in AngularJS

We can create custom AngularJS service with 'service' method and 'factory' method. Both are singletons, they gets instantiated once per app but there is a major difference between two,

Service is just a constructor function that will be called with 'new' keyword. When you’re using Service, Angular instantiates it behind the scenes with the ‘new’ keyword. Because of that, you’ll add properties to ‘this’ and the service will return ‘this’. When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service.

TeamModule.service('HelloWorldService'function () {
    this.HelloWorld = function (text) {
        return "Hello " + text + "!";


When you’re using a Factory you create an object, add properties/functions to it, then return that same object. When you pass this factory into your controller, those properties/functions on the object will now be available in that controller through your factory. Example below

TeamModule.factory('HelloWorldFactory'function () {
    return {
        HelloWorld: function (text) {
            return "Hi " + text + "!";

I strongly recommend to read my blog Services in AngularJS to know more about service.

No comments:

Post a Comment