angularJS 事件广播与接收

发送消息: $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);
    });
});
原文地址:https://www.cnblogs.com/zcynine/p/5170361.html