Melina Melina - 4 months ago 23
AngularJS Question

How can I pass some data from one controller to another peer controller

I have the following two peer controllers. There's no parent to these:

<div data-ng-controller="Controller1">

</div>

<div data-ng-controller="Controller2">
The value of xxx is: {{ xxx }}
</div>

angular.module('test')
.controller('QuestionsStatusController1',
['$rootScope', '$scope'
function ($rootScope, $scope) {
// How can I set the value of xxx in the HTML that's part of Controller2
}]);

angular.module('test')
.controller('QuestionsStatusController2',
['$rootScope', '$scope',
function ($rootScope, $scope) {
}]);


In controller 1 I want to update the value of the variable xxx in the HTML that's controlled by Controller2. Is there a way I can do this?

Answer

Definitely use a service to share data between controllers, here is a working example. $broadcast is not the way to go, you should avoid using the eventing system when there is a more appropriate way. Use a 'service', 'value' or 'constant' (for global constants).

http://plnkr.co/edit/ETWU7d0O8Kaz6qpFP5Hp

Here is an example with an input so you can see the data mirror on the page: http://plnkr.co/edit/DbBp60AgfbmGpgvwtnpU

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";
    });