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

前端 未结 19 2491
猫巷女王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 22:43

    Here's the quick and dirty way.

    // Add $injector as a parameter for your controller
    
    function myAngularController($scope,$injector){
    
        $scope.sendorders = function(){
    
           // now you can use $injector to get the 
           // handle of $rootScope and broadcast to all
    
           $injector.get('$rootScope').$broadcast('sinkallships');
    
        };
    
    }
    

    Here is an example function to add within any of the sibling controllers:

    $scope.$on('sinkallships', function() {
    
        alert('Sink that ship!');                       
    
    });
    

    and of course here's your HTML:

    
    

提交回复
热议问题