AngularJS Provider, Factory, Service, Value And Constant

Introduction

This article will help you understand the key differences among provider, factory, service, value and constant.

Step 1

Create a folder "Lab01" and create the files as mentioned below.

  1. HTML
  2. js
  3. min.js

Add the following code in index.HTML page.

  1. <!DOCTYPE html>  
  2. <html lang="en-US">  
  3. <head>  
  4.     <script src="angular.min.js"></script>  
  5.     <script src="app.js"></script>  
  6.     <style>  
  7.         .margin_top {  
  8.             margin-top: 10px;  
  9.         }  
  10.     </style>  
  11. </head>  
  12. <body>  
  13.     <div ng-app="myApp" >  
  14.         <table >  
  15.             <tr>  
  16.                 <td >  
  17.                     <div ng-controller="controller1" style="border:dashed;padding-bottom:100px;width:600px;">  
  18.                         <label>Enter your name :</label>  
  19.                         <input type="text" ng-model="name" ng-init="name='Dinesh Kushwaha'" />  
  20.                         <h1>{{message}}</h1>  
  21.                         <button ng-click="myProviderSayHello(name)" class="margin_top">Get Value From Provider</button>  
  22.                         <button ng-click="myFactorySayHello(name)" class="margin_top">Get Value From Factory</button>  
  23.                         <button ng-click="myServiceSayHello(name)" class="margin_top">Get Value From Service</button>  
  24.                         <hr />  
  25.                         <label >   
  26.                             Provider called {{pcounter}} times.<br/>  
  27.                             Factory called {{fcounter}} times.<br />  
  28.                             Service called {{scounter}} times.  
  29.                         </label>  
  30.                         <hr />  
  31.                         <label>  
  32.                             FullName : {{pfullName}}<br />  
  33.                             FullName : {{ffullName}}<br />  
  34.                             FullName : {{sfullName}}<br />  
  35.                             FullName : {{vfullName}}<br />  
  36.                             FullName : {{cfullName}}  
  37.                         </label>  
  38.                     </div>  
  39.                 </td>  
  40.                 <td>  
  41.                     <div ng-controller="controller2" style="border:dashed;padding-bottom:100px;width:600px;">  
  42.                         <label>Enter your name :</label>  
  43.                         <input type="text" ng-model="name" ng-init="name='Dinesh Kushwaha'" />  
  44.                         <h1>{{message}}</h1>  
  45.                         <button ng-click="myProviderSayHello(name)" class="margin_top">Get Value From Provider</button>  
  46.                         <button ng-click="myFactorySayHello(name)" class="margin_top">Get Value From Factory</button>  
  47.                         <button ng-click="myServiceSayHello(name)" class="margin_top">Get Value From Service</button>  
  48.                         <hr />  
  49.                         <label >  
  50.                             Provider called {{pcounter}} times.<br />  
  51.                             Factory called {{fcounter}} times.<br />  
  52.                             Service called {{scounter}} times.  
  53.                         </label>  
  54.                         <hr />  
  55.                         <label>  
  56.                             FullName    : {{pfullName}}<br />  
  57.                             FullName    : {{ffullName}}<br />  
  58.                             FullName    : {{sfullName}}<br />  
  59.                             FullName    : {{vfullName}}<br />  
  60.                             FullName    : {{cfullName}}  
  61.                         </label>  
  62.                     </div>  
  63.                 </td>  
  64.             </tr>  
  65.         </table>  
  66.     </div>  
  67. </body>  
  68. </html>  

Step 2

Add the following code in app.js 

  1. var app = angular.module("myApp", []);  
  2. var globalObject = { pcounter: 0, fcounter: 0, scounter: 0 };  
  3.   
  4. app.constant('appName', {  
  5.     appName: 'myApp',  
  6.     auther: 'Dinesh Kushwaha',  
  7.     fullName: 'Dinesh Kushwaha from constant',  
  8. });  
  9.   
  10. app.value('user', {  
  11.     userName: 'dinesh.singh',  
  12.     fullName: 'Dinesh Kushwaha from value',  
  13.     email: '2kush.dinesh@gmail.com',  
  14.     authenticationToken: '343sddjsdfwueiuyeiwbbzxcmb78687687'  
  15. });  
  16.   
  17. app.provider("sharedObjectFromProvider"function () {  
  18.     globalObject.pcounter++;  
  19.     var name = null;  
  20.     this.setName = function (newName) {  
  21.         name = newName;  
  22.     };  
  23.     this.$get = function () {  
  24.         return {  
  25.             message: name,  
  26.             sayHello: function (name) {  
  27.                 alert('Hello ' + name + '   You are in provider shared object');  
  28.             }  
  29.         };  
  30.     };  
  31. });  
  32.   
  33. //This is existing module.  
  34. function Person() {  
  35.     var _fullName = "Dinesh Kushwaha from factory.";  
  36.     this.fullName = _fullName;  
  37.     this.sayHello = function (name) {  
  38.         alert('Hello ' + name + '   You are in factory shared object');  
  39.     }  
  40. }  
  41.   
  42. //For existing reusable module use factory.  
  43. //Factory create shared object of existing module.  
  44. app.factory("sharedObjectFromFactory"function () {  
  45.     globalObject.fcounter++;  
  46.     return new Person();  
  47. });  
  48.   
  49. //For new shared module use service.  
  50. //Service build shared object from scratch.  
  51. app.service("sharedObjectFromService"function () {  
  52.     globalObject.scounter++;  
  53.     var _fullName = "Dinesh Kushwaha from service.";  
  54.     this.fullName = _fullName;  
  55.     this.sayHello = function (name) {  
  56.         alert('Hello ' + name + '   You are in service shared object');  
  57.     }  
  58. });  
  59.   
  60. //Controller 1  
  61. app.controller("controller1"function ($scope, sharedObjectFromProvider, sharedObjectFromFactory,  
  62.     sharedObjectFromService, appName, user) {  
  63.     $scope.message = "Controller 1";  
  64.   
  65.     $scope.myProviderSayHello = sharedObjectFromProvider.sayHello;  
  66.     $scope.myFactorySayHello = sharedObjectFromFactory.sayHello;  
  67.     $scope.myServiceSayHello = sharedObjectFromService.sayHello  
  68.   
  69.     $scope.pfullName = sharedObjectFromProvider.message;  
  70.     $scope.ffullName = sharedObjectFromFactory.fullName;  
  71.     $scope.sfullName = sharedObjectFromService.fullName;  
  72.     $scope.cfullName = appName.fullName;  
  73.     $scope.vfullName = user.fullName;  
  74.   
  75.     $scope.pcounter = globalObject.pcounter;  
  76.     $scope.fcounter = globalObject.fcounter;  
  77.     $scope.scounter = globalObject.scounter;  
  78. });  
  79.   
  80. //Controller 2  
  81. app.controller("controller2"function ($scope, sharedObjectFromProvider, sharedObjectFromFactory,  
  82.     sharedObjectFromService, appName, user) {  
  83.     $scope.message = "Controller 2";  
  84.   
  85.     $scope.myProviderSayHello = sharedObjectFromProvider.sayHello  
  86.     $scope.myFactorySayHello = sharedObjectFromFactory.sayHello  
  87.     $scope.myServiceSayHello = sharedObjectFromService.sayHello  
  88.   
  89.     $scope.pfullName = sharedObjectFromProvider.message;  
  90.     $scope.ffullName = sharedObjectFromFactory.fullName;  
  91.     $scope.sfullName = sharedObjectFromService.fullName;  
  92.     $scope.cfullName = appName.fullName;  
  93.     $scope.vfullName = user.fullName;  
  94.   
  95.     $scope.pcounter = globalObject.pcounter;  
  96.     $scope.fcounter = globalObject.fcounter;  
  97.     $scope.scounter = globalObject.scounter;  
  98. });  
  99.   
  100. app.config(['sharedObjectFromProviderProvider''appName',  
  101.     function (sharedObjectFromProviderProvider, appName) {  
  102.         sharedObjectFromProviderProvider.setName('Dinesh Kushwaha from config.');  
  103.     }]);  

Step 3

Download angular.min.js lib and reference it in index.html page as "<script src="angular.min.js"></script>".

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

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

When should we use them?

Provider & Constant

  1. If you want a shared object accessible in "config({ });"then you can use them because only provider & constant can be accessible in config.
  2. 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({})). 
  3. 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

  1. var app = angular.module("myApp", []);  
  2. var globalObject = { pcounter: 0, fcounter: 0, scounter: 0 };  
  3.   
  4. app.constant('appName', {  
  5.     appName: 'myApp',  
  6.     auther: 'Dinesh Kushwaha',  
  7.     fullName: 'Dinesh Kushwaha from constant',  
  8. });  
  9.   
  10. app.provider("sharedObjectFromProvider"function () {  
  11.     globalObject.pcounter++;  
  12.     var name = null;  
  13.     this.setName = function (newName) {  
  14.         name = newName;  
  15.     };  
  16.     this.$get = function () {  
  17.         return {  
  18.             message: name,  
  19.             sayHello: function (name) {  
  20.                 alert('Hello ' + name + '   You are in provider shared object');  
  21.             }  
  22.         };  
  23.     };  
  24. });   

How to use

  1. app.config(['sharedObjectFromProviderProvider''appName',  
  2.     function (sharedObjectFromProviderProvider, appName) {  
  3.         sharedObjectFromProviderProvider.setName('Dinesh Kushwaha from config.');  
  4.     }]);  

Factory

  1. If you want a shared object other than config; i.e. in controller, then you can use factory.
  2. If you have any existing JavaScript class or module and you want to re-use & create a shared object by using this class and module then you can use a factory.
  3. It is a singleton, instantiable (i.e. you can use new keywordto create an instance of an object.) not configurable (i.e. you cannot use this config({})). 

How to create

  1. var app = angular.module("myApp", []);  
  2. var globalObject = { pcounter: 0, fcounter: 0, scounter: 0 };  
  3.   
  4. //This is existing module.  
  5. function Person() {  
  6.     var _fullName = "Dinesh Kushwaha from factory.";  
  7.     this.fullName = _fullName;  
  8.     this.sayHello = function (name) {  
  9.         alert('Hello ' + name + '   You are in factory shared object');  
  10.     }  
  11. }  
  12.   
  13. //For existing reusable module use factory.  
  14. //Factory create shared object of existing module.  
  15. app.factory("sharedObjectFromFactory"function () {  
  16.     globalObject.fcounter++;  
  17.     return new Person();  
  18. });   

How to use

  1. //Controller 1  
  2. app.controller("controller1"function ($scope, sharedObjectFromProvider, sharedObjectFromFactory,  
  3.     sharedObjectFromService, appName, user) {  
  4.     $scope.myFactorySayHello = sharedObjectFromFactory.sayHello;  
  5.     $scope.ffullName = sharedObjectFromFactory.fullName;  
  6. });  

Service

  1. If you want to create a shared object from scratch, then you can use service because you cannot use existing class & module. 
  2. If you are in the early phase of application development, then you can use service to create a shared object. 
  3. It is a singleton but neither instantiable (i.e. you cannot use new keywordto create an instance of an object.) nor configurable (i.e. you cannot use this config({})).  

How to create

  1. var app = angular.module("myApp", []);  
  2. var globalObject = { pcounter: 0, fcounter: 0, scounter: 0 };  
  3.   
  4. //For new shared module use service.  
  5. //Service build shared object from scratch.  
  6. app.service("sharedObjectFromService"function () {  
  7.     globalObject.scounter++;  
  8.     var _fullName = "Dinesh Kushwaha from service.";  
  9.     this.fullName = _fullName;  
  10.     this.sayHello = function (name) {  
  11.         alert('Hello ' + name + '   You are in service shared object');  
  12.     }  
  13. });  

How to use

  1. //Controller 2  
  2. app.controller("controller2"function ($scope, sharedObjectFromProvider, sharedObjectFromFactory,  
  3.     sharedObjectFromService, appName, user) {  
  4.     $scope.message = "Controller 2";  
  5.     $scope.myServiceSayHello = sharedObjectFromService.sayHello  
  6.     $scope.sfullName = sharedObjectFromService.fullName;   
  7. });  

Value

  1. If you have any created JSON object & want to use it as a shared object, then you can use this to create a shared object.
  2. It is a singleton but neither instantiable (i.e. you cannot use new keywordto create an instance of an object.) nor configurable (i.e. you cannot use this config({})). 

How to create

  1. var app = angular.module("myApp", []);  
  2. var globalObject = { pcounter: 0, fcounter: 0, scounter: 0 };  
  3.   
  4. app.value('user', {  
  5.     userName: 'dinesh.singh',  
  6.     fullName: 'Dinesh Kushwaha from value',  
  7.     email: '2kush.dinesh@gmail.com',  
  8.     authenticationToken: '343sddjsdfwueiuyeiwbbzxcmb78687687'  
  9. });  

How to use

  1. //Controller 1  
  2. app.controller("controller1"function ($scope, sharedObjectFromProvider, sharedObjectFromFactory,  
  3.     sharedObjectFromService, appName, user) {  
  4.     $scope.vfullName = user.fullName;  
  5. });  

I hope you understood the key differences between provider, factory, service, value and constant.

If you still have any confusion\query\concern please feel free to leave your comment in the comment box, I will respond as soon as possible. 

AngularJS provides various options to create shared object although the uses are different you want to understand AngularJS at the expert level then you must keep a crystal clear understanding of basic concepts of AngularJS.

That all for this tutorial.

Summary

In this article, I discussed how we can create a TypeScript with RequireJS in ASP.NET Core application in C#. 

G
M
T
 
Text-to-speech function is limited to 200 characters