Search This Blog

2016-01-11

Angular JS Tutorial9: services,factory,provider

AngularJS Service, Factory or Provider all are used for the same purpose of creating utility function that can be used throughout the page with inject-able object. However, the way it is created and the way it is used are different. Here we shall try to understand them clearly.


AngularJS Service:
Angular Service is used to for sharing utility functions with the service reference in the controller. Service is singleton in nature so for once service only one instance is created in the browser and the same reference is used throughout the page.In the service, we create function names as property with this object.

AngularJS Factory :
The purpose of Factory is also same as Service however in this case we create a new object and add functions as properties of this object and at the end we return this object.

AngularJS Provider:
The purpose of this is again same however Provider gives the output of it's $get function.

Example :

9.html:

<!DOCTYPE html>
<html lang="en">
<head>
 <title>services,factory,provider</title>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
 <script src="9controller.js"></script>

</head>
<body ng-app="myapp" ng-controller="mycontroller">
 {{mymessage}}

</body>
</html>

9controller.js:
var app=angular.module('myapp',[]);

app.service('myservice',function(){
 this.mymessage='this is from my service';
}
);
app.factory('myfactory',function(){
 var factory={};
 factory.mymessage='this is from my factory';
 return factory;
}
);
app.provider('myprovider',function(){
 var m1='this is from my provider';
 return {
  setMessage:function(name){//1)its required,if we need set the value
   m1 += name;
  },
  $get:function(){
   return {
    message:m1
   }
  }
 }
});
//2)its required,if we need set the value
app.config(function(myproviderProvider){//ProviderSuffix
 myproviderProvider.setMessage("Manab");
});
app.controller('mycontroller',function($scope,myservice,myfactory,myprovider){
 $scope.mymessage=[myservice.mymessage,myfactory.mymessage,myprovider.message];
});
// app.controller('mycontroller',function($scope,myservice,myfactory){
//  $scope.mymessage='ddd';
// });


Output:


No comments: