發送消息: $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); }); });