发送消息: $scope.$emit(name, data) 或者 $scope.$broadcast(name, data);

接收消息: $scope.on(name,function(event,data){ });

区别: $emit 广播给父controller   $broadcast 广播给子controller

 

broadcast 是从发送者向他的子scope广播一个事件。

这里就是ParentController发送, ParentController 和 ChildController 会接受到, 而MainController是不会收到的

 

$emit 广播给父controller,父controller 是可以收到消息

$on 有两个参数function(event,msg)  第一个参数是事件对象,第二个参数是接收到消息信息

 

var app = angular.module('onBroadcastEvent', ['ng']);

app.controller('MainController', function($scope) {
    $scope.$on('To-MainController', function(event,msg) {
        console.log('MainController received:' + msg);
    });
});

app.controller('ParentController', function($scope) {
    $scope.click = function (msg) {
        $scope.$emit('To-MainController',msg + ',from ParentController to MainController');
        $scope.$broadcast('To-ChildController', msg + ',from ParentController to ChildController');
        $scope.$broadcast('To-BrotherController', msg + ',from ParentController to BrotherController');
    }
});

app.controller('ChildController', function($scope){
    $scope.$on('To-ChildController', function(event,msg) {
        console.log('ChildController received:' + msg);
    });
});

app.controller('BrotherController', function($scope){
    $scope.$on('To-BrotherController', function(event, msg) {
        console.log('BrotherController received:' + msg);
    });
});

 

相关文章:

  • 2021-06-10
  • 2021-12-10
  • 2021-10-20
  • 2022-12-23
  • 2021-07-29
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-09
  • 2022-12-23
  • 2021-12-28
  • 2021-09-24
  • 2021-10-02
  • 2022-12-23
相关资源
相似解决方案