Invoke one controller from another

后端 未结 3 528
渐次进展
渐次进展 2021-01-25 05:30

I am a total newbie in AngularJs, so please be patient with me.

I have the following angular App, which contains two controllers

(function () {
    angul         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 06:13

    you can active this is two way:

    First : $broadcast and $on

    //PUBLISHER
    angular.module('myApp').controller('CtrlPublish', ['$rootScope', '$scope',
    function ($rootScope, $scope) {
    
      $rootScope.$broadcast('topic', 'message');
    
    }]);
    
    //SUBSCRIBER
    angular.module('myApp').controller('ctrlSubscribe', ['$scope',
    function ($scope) {
    
      var unbind = $scope.$on('topic', function (event, arg) { 
        $scope.receiver = 'got your ' + arg;
      });
      $scope.$on('$destroy', unbind);
    }]);
    

    Second : Through common service

    angular.module('myApp', [], function($provide) {
        $provide.factory('msgBus', ['$rootScope', function($rootScope) {
            var msgBus = {};
            msgBus.emitMsg = function(msg) {
            $rootScope.$emit(msg);
            };
            msgBus.onMsg = function(msg, scope, func) {
                var unbind = $rootScope.$on(msg, func);
                scope.$on('$destroy', unbind);
            };
            return msgBus;
        }]);
    });
    

    and use it in controller like this:

    controller 1

    function($scope, msgBus) {
        $scope.sendmsg = function() {
            msgBus.emitMsg('somemsg')
        }
    }
    

    controller 2

    function($scope, msgBus) {
        msgBus.onMsg('somemsg', $scope, function() {
            // your logic
        });
    }
    

    From : Post

提交回复
热议问题