如何从一个控制器向另一个控制器发送消息

时间:2013-09-17 17:21:29

标签: angularjs

我有以下内容:

<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()

    }]);

我是否有办法在Controller1的HTML中点击,导致Controller2中的方法触发。请注意,我没有这些控制器的父控制器。这是因为我使用的是ui-router

1 个答案:

答案 0 :(得分:3)

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

   }]);