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

前端 未结 19 2492
猫巷女王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条回答
  •  猫巷女王i
    2020-11-21 22:48

    The top answer here was a work around from an Angular problem which no longer exists (at least in versions >1.2.16 and "probably earlier") as @zumalifeguard has mentioned. But I'm left reading all these answers without an actual solution.

    It seems to me that the answer now should be

    • use $broadcast from the $rootScope
    • listen using $on from the local $scope that needs to know about the event

    So to publish

    // EXAMPLE PUBLISHER
    angular.module('test').controller('CtrlPublish', ['$rootScope', '$scope',
    function ($rootScope, $scope) {
    
      $rootScope.$broadcast('topic', 'message');
    
    }]);
    

    And subscribe

    // EXAMPLE SUBSCRIBER
    angular.module('test').controller('ctrlSubscribe', ['$scope',
    function ($scope) {
    
      $scope.$on('topic', function (event, arg) { 
        $scope.receiver = 'got your ' + arg;
      });
    
    }]);
    

    Plunkers

    • Regular $scope syntax (as you see above)
    • new Controller As syntax

    If you register the listener on the local $scope, it will be destroyed automatically by $destroy itself when the associated controller is removed.

提交回复
热议问题