Wscats / angular-tutorial

:rabbit:Some of the angular tutorial - 《Angular学习笔记》
387 stars 125 forks source link

$broadcast,$emit and $on #11

Open Wscats opened 8 years ago

Wscats commented 8 years ago

发送事件可以用 向父控制器传递信息 $scope.$emit('name', 'args'); 或者是 向子控制器传递信息 $scope.$broadcast('name', 'args'); name:事件的名字 args:事件所需要传递的参数 接受事件可以用(仅此一个方法可以接受事件)

接受来自于子或父传来的信息
$scope.$on('name',function(event,data){
//从$emit或者$broadcast中获取的args事件传递来的信息
})

例子如下 注意 bodyCtrl为indexCtrl的父 indexChildCtrl为indexCtrl的子

<!DOCTYPE html>
<html ng-app="wsscat">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <script type="text/javascript" src="js/angular.js"></script>

    <body ng-controller="bodyCtrl">
        <article ng-controller="indexCtrl">
            {{name}}
            <button ng-click="click()">Ok</button>
            <section ng-controller="indexChildCtrl">
                <input ng-model="name" ng-change="changName()" />
                {{name}}
            </section>
        </article>

        <article ng-controller="indexBrotherCtrl">
            {{name}}
        </section>
        </article>
    </body>
    <script>
        var app = angular.module('wsscat', []);
        app.controller('bodyCtrl', function($scope) {
            $scope.$on('to-parent', function(event, data) {
                console.log('I am the parent, I got it', data);
            });
        })
        app.controller('indexCtrl', function($scope) {
            $scope.name = "wsscat";
            $scope.click = function() {
                //向下广播事件
                $scope.$broadcast('to-child', 'haha');
                //向上广播事件
                $scope.$emit('to-parent', 'hehe');
            }
            //子控制器indexChildCtrl改变名字后,向上发送to-parent-name事件委托告诉indexCtrl,$scope.name值已经发生改变,并一起作出改变
            $scope.$on('to-parent-name', function(event, data) {
                console.log('I am the parent to-parent-name, I got it', data);
                $scope.name = data;
            });
        })

        app.controller('indexChildCtrl', function($scope) {
            $scope.$on('to-child', function(event, data) {
                console.log('I am the child, I got it', data);
            });
            $scope.changName = function() {
                $scope.$emit('to-parent-name', $scope.name);
            }
        })

        app.controller('indexBrotherCtrl', function($scope,$rootScope) {
            $rootScope.$on('to-parent', function(event, data) {
                console.log('I am the parent from $rootScope, I got it', data);
                $scope.name = data;
            });
        })

        app.service("hiEventService", function($rootScope) {
            this.broadcast = function() {
                $rootScope.$broadcast("hi")
            }
            this.listen = function(callback) {
                $rootScope.$on("hi", callback)
            }
        })
    </script>
</html>

上面的结果,当我们按下按钮,indexCtrl分别向它的父于子进行消息传递,打印信息如下 这里写图片描述