微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angular中$emit与$broadcast详解

angularjs 中 broadcast emit $on的处理思想

  • 对于Angular的controll之间的通信方式,我们可以常见有有几种方式,如可以通过 rootScope scope的作用域,当然还有一种个人觉得很好的通信方式就是 broadcast, emit,$on来监听;

  • broadcast emit方式的区别
    broadcast广@H_393_404@controller emit与$broadcast方式相反,是子级controller发布一个消息事件,父级controller监听的函数执行;
    两种方式平级的controller都不能收到消息事件,注意同一个controller里面都是可以捕获到消息事件的;
    父子级controller

<div ng-controller="ParentCtrl">                  //父级  
    <div ng-controller="SelfCtrl">                //自己  
        <a ng-click="click()">click me</a>  
        <div ng-controller="ChildCtrl"></div>     //子级  
    </div>  
    <div ng-controller="broCtrl"></div>           //平级  
</div>

javascript如下:

phonecatControllers.controller('SelfCtrl',function($scope) {  
    $scope.click = function () {  
        $scope.$broadcast('to-child','child');  
        $scope.$emit('to-parent','parent');  
    }  
});  

phonecatControllers.controller('ParentCtrl',function($scope) {  
    $scope.$on('to-parent',function(d,data) {  
        console.log(data);         //父级能得到值 
    });  
    $scope.$on('to-child',data) {  
        console.log(data);         //子级得不到值 
    });  
});  

phonecatControllers.controller('ChildCtrl',function($scope){  
    $scope.$on('to-child',data) {  
        console.log(data);         //子级能得到值 
    });  
    $scope.$on('to-parent',data) {  
        console.log(data);         //父级得不到值 
    });  
});  

phonecatControllers.controller('broCtrl',function($scope){  
    $scope.$on('to-parent',data) {  
        console.log(data);        //平级得不到值 
    });  
    $scope.$on('to-child',data) {  
        console.log(data);        //平级得不到值 
    });  
});

一个controller里面

<div ng-controller="Ctrl">
        <h1>{{message1}}</h1>
        <h2>{{message2}}</h2>
    </div>

js代码

angular.module('app',[])
        .controller('Ctrl',['$scope',function($scope) {
            $scope.$on('msg1',function(e,msg) {
                $scope.message1 = msg;
            });
            $scope.$on('msg2',msg) {
                $scope.message2 = msg;
            });
            $scope.$emit('msg1','Hello Angular!');
            $scope.$broadcast('msg2','Angular is magic!')
        }]);

注意:
相比 emit broadcast广播方法要消耗更多的资源,因为广播事件会深入到该作用域的所有子孙作用域,跟单路径冒泡的 emit broadcast方法

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐