作用域事件路由与广播基于$emit()和$broadcast()方法

 
 

    事件路由的方向是从子作用域到父作用域,而时间广播的方向是从父作用域的方向到子作用域的方向。刚好相反。事件路由,事件广播,注意了,主语是事件。也就是说,事件可以从子作用域流到父作用域,也可以从父作用域流到子作用域。

<html ng-app = "appModule">
    <head>
        <meta charset="utf-8">
        <script type="text/javascript" src="../angular-1.6.9/angular.js"></script>
    </head>
    <body>
        <div ng-controller="parentController">
            <div ng-controller="childController">
                <button ng-click="postEvent()">emit</button>
            </div>
        </div>
        <div ng-repeat="person in people">
            <input type="text" ng-model="person.age"/>{{person.age}}
        </div>
    </body>
    <script type="text/javascript">
        var appModule = angular.module('appModule', []);
        appModule.controller('parentController', function($scope) {
            /*父作用域监听子作用域,通过$on方法*/
            /*注意父作用域和子作用域的事件方法相同都是initInfo*/
            $scope.$on("initInfo", function(event, data) {
                console.log("接收到子作用域的信息");
                console.log(data);
            });
        });
        appModule.controller('childController', function($scope) {
            /*子作用域将事件通过$emit方法发送到父作用域*/
            $scope.postEvent = function() {
                $scope.$emit("initInfo", {name:'jane', age:24});
            }
        });
    </script>
</html>
<html ng-app = "appModule">
    <head>
        <meta charset="utf-8">
        <script type="text/javascript" src="../angular-1.6.9/angular.js"></script>
    </head>
    <body>
        <div ng-controller="parentController">
            <span>父作用域</span><br>
            <button ng-click="postEvent()">emit</button>
            <div ng-controller="childController1">
                <span>子作用域1</span><br>
            </div>
            <div ng-controller="childController2">
                <span>子作用域2</span><br>
            </div>
        </div>
    </body>s
    <script type="text/javascript">
        var appModule = angular.module('appModule', []);
        appModule.controller('parentController', function($scope) {
            $scope.postEvent = function() {
                /*父作用域要广播一个事件initInfo*/
                $scope.$broadcast('initInfo', {name:'wuhan', age:23});
            }
        });
        appModule.controller('childController1', function($scope) {
            /*子作用域要监听一个事件initInfo*/
            $scope.$on("initInfo", function(event, data) {
                console.log("childController1");
                console.log(data);
            });
        });
        appModule.controller('childController2', function($scope) {
            /*子作用域要监听一个事件initInfo*/
            $scope.$on("initInfo", function(event, data) {
                console.log("childController2");
                console.log(data);
            });
        });
    </script>
</html>


猜你喜欢

转载自blog.csdn.net/qq_23143555/article/details/80218788
今日推荐