$ broadcast和$ emit中的作用域如何工作

时间:2017-01-10 06:44:05

标签: angularjs

<!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从scope更改为rootscope时,代码无法正常工作,因为$ on是从事件中接收的,它应该已接受来自广播的值,因为它在子控制器中存在 请务必明白我的疑虑

1 个答案:

答案 0 :(得分:2)

firstCtrlsecondCtrl

的孩子

在这种情况下:

  • secondCtrl 广播消息时,子范围(本例中为firstCtrl范围)可以使用该消息。
  • secondCtrl 发出消息时,它的父作用域(在这种情况下为rootScope - 可以使用它 - 这是根父母您应用中的范围)

因此,如果您想将其发送到rootScope,则应使用$emit

See docs about $broadcast and $emit

相关问题