Search This Blog


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 :


<!DOCTYPE html>
<html lang="en">
 <script src=""></script>
 <script src="9controller.js"></script>

<body ng-app="myapp" ng-controller="mycontroller">


var app=angular.module('myapp',[]);

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


No comments: