$broadcast和$emit中的范围如何工作


<!DOCTYPE html>
<html>
   <head>
      <title>Broadcasting</title>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
      <script>
         var app = angular.module('app', []);
         app.controller("firstCtrl", function ($scope,$rootScope) {
             $rootScope.$on('eventName', function (event, args) {
                 $scope.message = args.message;
                 console.log($scope.message);
             });
         });
         app.controller("secondCtrl", function ($scope,$rootScope) {
                 $scope.handleClick = function (msg) {
                 $scope.$broadcast('eventName', { message: msg });
             };
         });
      </script>
   </head>
   <body ng-app="app">
      <div ng-controller="secondCtrl" style="border:2px solid #E75D5C;padding:5px;">
         <h1>parent Controller</h1>
         <input ng-model="msg">
         <button ng-click="handleClick(msg);">Emit</button>
         <div ng-controller="firstCtrl" style="border:2px solid #428bca;padding:5px;">
            <h1>Child Controller</h1>
            <p>Emit Message :{{message}} </p>
            <br /> 
         </div>
      </div>
   </body>
</html>

当我$on范围更改为rootscope时,代码不起作用,因为$on正在接收来自事件,它应该接受广播的值,因为它存在于子控制器中请澄清我的疑虑

firstCtrlsecondCtrl的孩子

在这种情况下:

  • secondCtrl广播消息时,它将可用于其子作用域(在本例中为firstCtrl作用域)
  • secondCtrl发出消息时,它将可用于其父范围(在本例中rootScope - 这是应用中的根父范围)

因此,如果你想把它放到 rootScope,你应该使用 $emit

查看有关$broadcast$emit的文档

最新更新