angular events

<!doctype html>
<html ng-app="app">
    <head>
    <meta charset="utf-8">
        <script src="./angular-1.5.8/angular.js"></script>
    </head>
    <body>
        <div ng-controller="ParentCtrl">                 
            <div ng-controller="SelfCtrl">                
                <a ng-click="click($event)">click me</a>
                <div ng-controller="ChildCtrl"></div>     
            </div>
            <div ng-controller="BroCtrl"></div>           
        </div>
    </body>
</html>
<script>
var phonecatControllers = angular.module('app',[]);
phonecatControllers.controller('SelfCtrl', function($scope) {
    $scope.click = function () {
        $scope.$broadcast('to-child', 'child');
        $scope.$emit('to-parent', 'parent');
    }
    $scope.$on('to-parent', function(event,data) {
        console.log('SelfCtrl to-parent', data);         //父级能得到值
    });
    $scope.$on('to-child', function(event,data) {
        console.log('SelfCtrl to-child', data);         //父级能得到值
    });
});
phonecatControllers.controller('ParentCtrl', function($scope) {
    $scope.$on('to-parent', function(event,data) {
        console.log('ParentCtrl to-parent', data);         //父级能得到值
    });
    $scope.$on('to-child', function(event,data) {
        console.log('ParentCtrl to-child',data);         //子级得不到值
    });
});
phonecatControllers.controller('ChildCtrl', function($scope){
    $scope.$on('to-child', function(event,data) {
        console.log('ChildCtrl to-child',data);         //子级能得到值
    });
    $scope.$on('to-parent', function(event,data) {
        console.log('ChildCtrl to-parent',data);         //父级得不到值
    });
});
phonecatControllers.controller('BroCtrl', function($scope){
    $scope.$on('to-parent', function(event,data) {
        console.log('BroCtrl to-parent',data);        //平级得不到值
    });
    $scope.$on('to-child', function(event,data) {
        console.log('BroCtrl to-child',data);        //平级得不到值
    });
});
</script>

Output:

  1. SelfCtrl to-child child

  2. ChildCtrl to-child child

  3. SelfCtrl to-parent parent

  4. ParentCtrl to-parent parent

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值