angularjs 事件传播

broadcast

要把事件向下传递(从父作用域到子作用域),我们使用$broadcast()函数。

$broadcast()方法自身带有两个参数。

1. name(字符串)
要发出的事件名称。
2. args(集合)
一个参数的集合,作为对象传递到事件监听器中。

使用$emit来冒泡事件

要把事件沿着作用域链向上派送(从子作用域到父作用域),我们要使用$emit()函数

$emit()方法带有两个参数。
1. name(字符串)
要发出的事件名称。
2. args(集合)
一个参数的集合,作为对象传递到事件监听器中

angular.module('TestApp', ['ng'])
.controller('ParentCtrl', function($scope) {
 $scope.$on('to-parent', function(e, d) {
    console.log('we are the parent, I got it', d);
 });
})
.controller('SelfCtrl', function($scope) {
  $scope.click = function () {
//触发事件 $scope.$broadcast(
'to-child', 'haha'); $scope.$emit('to-parent', 'hehe'); } }) .controller('ChildCtrl', function($scope){
//响应事件 $scope.$on(
'to-parent', function(e, d) { console.log('关我毛事'); }); }) .controller('BroCtrl', function($scope){ $scope.$on('to-parent', function(e, d) { console.log('关我毛事'); }); }) ;

 

posted @ 2016-02-23 15:15  程序猿进化之路  阅读(137)  评论(0)    收藏  举报