Skip to content
Loading
AngularJS: service and factory is singleton ?  
  •   
  • var myApp = angular.module('myApp', []);  
  •   
  • myApp.factory('Data', function(){  
  •   
  • var service = {  
  • FirstName: '',  
  • setFirstName: function(name) {  
  • // this is the trick to sync the data  
  • // so no need for a $watch function  
  • // call this from anywhere when you need to update FirstName  
  • angular.copy(name, service.FirstName);  
  • }  
  • };  
  • return service;  
  • });  
  •   
  •   
  • // Step 1 Controller  
  • myApp.controller('FirstCtrl', function( $scope, Data ){  
  • $scope.setData = function() {  
  • Data.FirstName='Tridip';  
  • };  
  • });  
  •   
  • // Step 2 Controller  
  • myApp.controller('SecondCtrl', function( $scope, Data ){  
  • $scope.FirstName = Data.FirstName;  
  •   
  • $scope.getData = function() {  
  • alert('get data '+Data.FirstName)  
  • };  
  • }); 
  • i asked totally different question. i am looking for a code sample which show me that service and factory is singleton.
     
    i am not looking for ling which tell me what is service and factory or difference between them.
  • Manikandan Murugesan
    Refer this link for create the singleton: https://blog.jdriven.com/2013/03/how-to-create-singleton-angularjs-services-in-4-different-ways/
     
    This link for refer service vs factory : https://stackoverflow.com/questions/13762228/confused-about-service-vs-factory