tri_inn

tri_inn

  • NA
  • 1.2k
  • 233.5k

AngularJS: factory and share data between controllers

Jun 12 2017 9:34 AM
My question is AngularJS: Why people prefer factory to share data between controllers
 
 
i am new in angular. so trying to know how to share data between two controller and search google. i visited few pages and found most of the time people use factory to share data. i just like to know can't we do it by service instead of factory ?
1st example

  1. <div ng-controller="FirstCtrl">  
  2. <input type="text" ng-model="data.firstName">  
  3. <br>Input is : <strong>{{data.firstName}}</strong>  
  4. </div>  
  5. <hr>  
  6. <div ng-controller="SecondCtrl">  
  7. Input should also be here: {{data.firstName}}  
  8. </div>  
  9.   
  10. myApp.factory('MyService', function(){  
  11. return {  
  12. data: {  
  13. firstName: '',  
  14. lastName: ''  
  15. },  
  16. update: function(first, last) {  
  17. // Improve this method as needed  
  18. this.data.firstName = first;  
  19. this.data.lastName = last;  
  20. }  
  21. };  
  22. });  
  23.   
  24. // Your controller can use the service's update method  
  25. myApp.controller('SecondCtrl', function($scope, MyService){  
  26. $scope.data = MyService.data;  
  27.   
  28. $scope.updateData = function(first, last) {  
  29. MyService.update(first, last);  
  30. }  
  31. }); 


2nd example

  1. var myApp = angular.module('myApp', []);  
  2.   
  3. myApp.factory('Data', function(){  
  4.   
  5. var service = {  
  6. FirstName: '',  
  7. setFirstName: function(name) {  
  8. // this is the trick to sync the data  
  9. // so no need for a $watch function  
  10. // call this from anywhere when you need to update FirstName  
  11. angular.copy(name, service.FirstName);  
  12. }  
  13. };  
  14. return service;  
  15. });  
  16.   
  17.   
  18. // Step 1 Controller  
  19. myApp.controller('FirstCtrl', function( $scope, Data ){  
  20.   
  21. });  
  22.   
  23. // Step 2 Controller  
  24. myApp.controller('SecondCtrl', function( $scope, Data ){  
  25. $scope.FirstName = Data.FirstName;  
  26. }); 
examples are taken from this url https://stackoverflow.com/questions/21919962/share-data-between-angularjs-controllers

please guide me. 
 

Answers (1)