0

How to share values between two controllers in angular. My scenario has two controllers and one service. When the user clicks on a button a first controller must create a random number and pass it to another controller.

Here is my sample code:

var app = angular.module('app', []);
app.controller("FirstController", function ($scope,sharedDateRange)  
  {    
      $scope.test = function(){
          sharedDateRange.setData();
      }
        
  });

app.controller("SecondController", function ($scope,sharedDateRange) {
    var data=[];
    data = sharedDateRange.getData();
    alert(data);
});


app.service('sharedDateRange', function ($http) {
var data=[];
return {
    setData: function () {
            data = Math.floor(Math.random() * 6) + 1;
        }
    ,
    getData: function(){
        return data;
    }
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <div ng-controller="FirstController">
        <button ng-click="test()"> Click</button>
    </div>
    <div ng-controller="SecondController">
        <span>{{data}}</span>
    </div>
</div>
Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
Emil
  • 423
  • 1
  • 12
  • 34

3 Answers3

1

Did you mean that when the value has change, The 2nd controller must get the new value? I use $broadcast and $on for it.

app.controller("FirstController", function ($scope,$rootScope,sharedDateRange)  
  {    
      $scope.test = function(){
          sharedDateRange.setData();
          $rootScope.$broadcast('changeValue');
      }

  });

app.controller("SecondController", function ($scope,sharedDateRange) {
    var data=[];
    data = sharedDateRange.getData();
    $scope.data = data;

    var cleanup = $scope.$on('changeValue', function() {
      console.log("get");
      $scope.data = sharedDateRange.getData();
    })

   //make sure to destroy to avoid memory leaks
    $scope.$on('$destroy', cleanup);
});

html:

<div ng-controller="FirstController">
   <button ng-click="test()">create random number</button>  
</div>
<div ng-controller="SecondController">
   {{data}}
</div>

working demo here

Vicruz
  • 321
  • 1
  • 12
  • 1
    if this is what you are looking for, please mark this as your answer :). – Vicruz Mar 10 '15 at 09:45
  • ok. my data read from database. when i consol.log($scope.data) that read from db it display undefind. how to manipulate $scope.data? – Emil Mar 10 '15 at 09:54
  • 1
    maybe because your console execute first rather than getting the data in database. Can you show me how you retrieve data from your database? – Vicruz Mar 10 '15 at 10:02
  • in service : setData: function () { $http.get('/getData').success(function(response){ data = response.data; }) }, – Emil Mar 10 '15 at 10:05
  • i read from db list. how manipulate it in second Ctrl? – Emil Mar 10 '15 at 10:10
  • 1
    try to check this one. http://stackoverflow.com/questions/21487413/angularjs-use-http-in-service-returns-reference-instead-of-actual-data – Vicruz Mar 10 '15 at 10:33
0

Place the setdata() in the service and simply access it is secondController.

Machiavelli
  • 411
  • 4
  • 15
0

The problem with your code is when you run your HTML page, it runs firstCtrl and secondCtrl one after another because you have set them in your HTML code. So according to your code what happens when your firstCtrl runs, it doesn't set any random value to data. and same time your secondCtrl also runs and it doesn't get any value.

I have change your code a bit. simple code. I have removed buttons click event. check this code. it is simple and easy to understand on your own.

HTML

<div ng-app="app">
    <div ng-controller="FirstController">

    </div>
    <div ng-controller="SecondController">
        <span>{{data}}</span>
    </div>
</div>

.js

var app = angular.module('app', []);
app.controller("FirstController", function ($scope,sharedDateRange)  
  {    
         sharedDateRange.setData();
  });

app.controller("SecondController", function ($scope,sharedDateRange) {
    $scope.data=sharedDateRange.getData();
    console.log($scope.data);
});


app.service('sharedDateRange', function ($http) {
var data="";
return {
    setData: function () {
        debugger;
          data = Math.floor(Math.random() * 6) + 1;
        }
    ,
    getData: function(){
        return data;
    }
}
});

https://jsfiddle.net/codu16t5/

micronyks
  • 54,797
  • 15
  • 112
  • 146