AngularJS service vs factory – with example

Also read my answer on stackoverflow (angular.service vs angular.factory).

What is an AngularJS service or factory?

Singleton.

Yes! That one word is enough to define AngularJS services. The purpose of AngularJS service / factory function is to generate a single object or function that represents the service to rest of the application. That object or function is passed as a parameter to any other factory function which specifies a dependency on this service.

Services

Syntaxmodule.service('serviceName', function);

Result: When declaring serviceName as an injectable argument you will be provided with the instance of a function passed to module.service.

Usage: Could be useful for sharing utility functions that are useful to invoke by simply appending () to the injected function reference. Could also be run with injectedArg.call(this) or similar.

Example:

Factories

Syntaxmodule.factory('factoryName', function);

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

Usage: Could be useful for returning a ‘class’ function that can then be new’ed to create instances.

 
Here is a running code on jsfiddle which you can test and play with.

 

  • Pingback: angular:service/factory | Annotary()

  • Richard

    wow this is the best and most simplified example. Thank you, this helped me a lot!

  • Henk

    I would advise against using global functions for your controllers though.

    angular.module(‘…’).controller(‘HelloCtrl’, function() {

    });

  • Thank you so much… going to a “separate files” version. 🙂

  • I must agree this is the best example found yet. It’s simple and clear.

  • Thamothara Kannan

    Hi sir i want one solution ,how to share text in G+

  • mila gorodetsky

    I’m trying the service example and I’m getting an error ” Cannot read property ‘sayHello’ of undefined” coming from HelloCtrl 🙁

  • Chandra Sekar

    Thanks. its working fine.

  • Joe

    Best explaination

  • Awesome post!! Thank you!

    It might help to others http://goo.gl/XZPJ4u

    • Reena Singh

      Its very helpful link for me thank you! @disqus_uAfbQsrO5I:disqus

  • Marcelo Lazaroni

    Awesome. Thank you for that.

  • Jag

    This is great post cover service and factory versions. Just for future readers, I came across this video which covers factory, service and provider methodologies in developing AngularJS Custom Services. Hopefully, it helps others:

    • rahu

      thanks

  • Himanshu Pandey

    I believe there is one more thing-: Service is beneficial working with classes, since it is a constructor function where as functions are not. Functions explicitly returns an object. for eg, services are useful in working with ECMAScript 6 classes.

  • Saffron AmAr

    not bad,,,,,,, bro