加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular中$emit与$broadcast详解

发布时间:2020-12-17 10:08:41 所属栏目:安全 来源:网络整理
导读:angularjs 中 b r o a d c a s t 与 emit $on的处理思想 对于Angular的controll之间的通信方式,我们可以常见有有几种方式,如可以通过 r o o t S c o p e , 还 有 通 过 scope的作用域,当然还有一种个人觉得很好的通信方式就是 b r o a d c a s t , emit,

angularjs 中 broadcast emit $on的处理思想

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

  • broadcast emit方式的区别
    broadcast广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方法

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读