user1943020
user1943020

Reputation:

How can I send a message from one controller to another peer controller

I have the following:

<div data-ng-controller="Controller1">
   <div class="button" 
        data-ng-click="action2()">
   </div>
</div>

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

</div>
angular.module('test')
   .controller('QuestionsStatusController1',
    ['$rootScope', '$scope',
    function ($rootScope, $scope) {

    }]);

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

         // I need some way to receive the action2()

    }]);

Is there a way I can make a click in the HTML of Controller1 cause a method to fire in Controller2. Note that I do not have a parent controller to either of these controllers. That's due to the fact I am using ui-router.

Upvotes: 2

Views: 483

Answers (1)

inzurrekt
inzurrekt

Reputation: 526

angular.module('test')
    .controller('QuestionsStatusController1',
    ['$rootScope', '$scope', '$resource', '$state',
    function ($rootScope, $scope, $resource, $state) {

        $scope.action2 = function() {
            $rootScope.$broadcast('action2@QuestionStatusController1');
        }

    }]);

angular.module('test')
   .controller('QuestionsStatusController2',
   ['$rootScope', '$scope', '$resource', '$state',
   function ($rootScope, $scope, $resource, $state) {

    $rootScope.$on('action2@QuestionStatusController1', function {
         //write your listener here
    })

   }]);

Upvotes: 3

Related Questions