-2

I am new to angular js and its services so please bear with this basic question. Please read comment inside code to understand what I need.

 .controller('ctrlr1', function($scope, myservice) {
     var a = "abc";       
 })
 .controller('ctrl2', function ($scope, myservice) {
      // how to get value of a 
 })
 .service('myservice', function() {
      //what goes here?
 });

Thanks in advance

Nitheesh
  • 19,238
  • 3
  • 22
  • 49
sam
  • 688
  • 1
  • 12
  • 35
  • 2
    How to transfer data between controllers? Look at this http://stackoverflow.com/questions/21919962/share-data-between-angularjs-controllers – Nitheesh Dec 22 '16 at 06:09

2 Answers2

1

Basic sharing by angular services

 .controller('ctrlr1', function($scope, myservice) {
    var a = "abc";
    var b = 123;
    myservice.myData = a;
    myservice.myDataB = b;
  })
  .controller('ctrl2', function ($scope, myservice) {
    // how to get value of a 
    console.log(myservice.myData);
    console.log(myservice.myDataB);
  })
  .service('myservice', function() {
    //what goes here?
    this.myData = '';
    this.myDataB = 0;
  });
M. Junaid Salaat
  • 3,765
  • 1
  • 23
  • 25
  • what if I have another variable in `ctrlr1` say `var b = 123`. How to pass both variables and access it in second controller – sam Dec 22 '16 at 06:28
  • Same as the first variable we saved in `myData` lets say a new property in `myservice` `myDataB`. I'll edit my answer please review that. – M. Junaid Salaat Dec 22 '16 at 06:43
  • I did it this way `myservice.myData = {va:a,vb:b}` then retrieved it as `myservice.myData.va` or `myservice.myData.vb`. – sam Dec 22 '16 at 08:03
  • would you answer this ques plz [link](http://stackoverflow.com/questions/41284584/using-scope-into-a-service) – sam Dec 22 '16 at 13:49
0

You can use myservice because its the efficient way but don't use $brodcast.

Here is an example:-

var testModule = angular.module('testmodule', []);

testModule
   .controller('QuestionsStatusController1',
    ['$rootScope', '$scope', 'myservice',
    function ($rootScope, $scope, myservice) {
       $scope.myservice = myservice;   
    }]);

testModule
   .controller('QuestionsStatusController2',
    ['$rootScope', '$scope', 'myservice',
    function ($rootScope, $scope, myservice) {
      $scope.myservice = myservice;
    }]);

testModule
    .service('myservice', function() {
      this.xxx = "yyy";
    }); 
Codesingh
  • 3,316
  • 1
  • 11
  • 18