Sharing Top Content from the Angular-sphere.

AngularJS Provider, Factory, Service, Value And Constant

  • This article will help you understand the key differences among provider, factory, service, value and constant.
  • Add the following code in index.HTML page.
  • Step 2 – – Add the following code in app.js – – Step 3 – – Download angular.min.js lib and reference it in index.html page as “".

    Now run the index.html in Chrome web browser or any web browser & you will see the following result:

    If you see the above screenshot then you will see a provider, factory, and service gets called only once for two different controllers. They are shared objects and singleton in nature. The same thing applies to value & constant.

    When should we use them?

    If you want a shared object accessible in "config({ });"then you can use them because only provider & constant can be accessible in config.

    The provider is a singleton, instantiable (i.e. you can use the new keyword to create an instance of an object.) and configurable (i.e. you can use this config({})). 

    Constant is singleton, configurable (i.e. you can use this config({})) but not instantiable (i.e. you cannot use new keyword to create instance of object.) 

    How to create

    How to use

    If you want a shared object other than config; i.e. in controller, then you can use factory.

    ...

    AngularJS Provider, Factory, Service, Value And Constant