Usage of $broadcast(), $emit() And $on() in AngularJS

后端 未结 3 588
陌清茗
陌清茗 2020-11-27 12:25

I understand that $Broadcast(), $Emit() And $On() are used to raise an event in one controller and handling in another controller. If

3条回答
  •  遥遥无期
    2020-11-27 12:50

    This little example shows how the $rootScope emit a event that will be listen by a children scope in another controller.

    (function(){
    
    
    angular
      .module('ExampleApp',[]);
    
    angular
      .module('ExampleApp')
      .controller('ExampleController1', Controller1);
    
    Controller1.$inject = ['$rootScope'];
    
    function Controller1($rootScope) {
      var vm = this, 
          message = 'Hi my children scope boy';
    
      vm.sayHi = sayHi;
    
      function sayHi(){
        $rootScope.$broadcast('greeting', message);
      }
    
    }
    
    angular
      .module('ExampleApp')
      .controller('ExampleController2', Controller2);
    
    Controller2.$inject = ['$scope'];
    
    function Controller2($scope) {
      var vm = this;
    
      $scope.$on('greeting', listenGreeting)
    
      function listenGreeting($event, message){
        alert(['Message received',message].join(' : '));
      }
    
    }
    
    
    })();
    

    http://codepen.io/gpincheiraa/pen/xOZwqa

    The answer of @gayathri bottom explain technically the differences of all those methods in the scope angular concept and their implementations $scope and $rootScope.

提交回复
热议问题