Abhishek
Abhishek

Reputation: 351

How does scopes in $broadcast and $emit works

<!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>

when i change $on from scope to rootscope the code is not working,since $on is recieving from event ,it should have accepted the value from broadcast since its present in child controller plz do clear my doubts

Upvotes: 0

Views: 196

Answers (1)

Ovidiu Dolha
Ovidiu Dolha

Reputation: 5423

firstCtrl is a child of secondCtrl

In this case:

  • When secondCtrl broadcasts a message, it will be available to its children scopes (firstCtrl scope in this case)
  • When secondCtrl emits a message, it will be available to its parent scopes (rootScope in this case - which is the root parent scope in your app)

Therefore, if you want to get it to rootScope, you should use $emit.

See docs about $broadcast and $emit

Upvotes: 2

Related Questions