What's the correct way to communicate between controllers in AngularJS?

前端 未结 19 2783
猫巷女王i
猫巷女王i 2020-11-21 22:02

What\'s the correct way to communicate between controllers?

I\'m currently using a horrible fudge involving window:

function StockSubgro         


        
19条回答
  •  攒了一身酷
    2020-11-21 23:03

    Since defineProperty has browser compatibility issue, I think we can think about using a service.

    angular.module('myservice', [], 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
          });
      }
      

提交回复
热议问题