Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Understanding $emit, $broadcast in AngularJS with example

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 590
    Comment on it

    The services yield by Anjularjs which can be utilized for communication based on event between controllers are $on, $emit, and $broadcast. These are under the publish/subscribe design pattern of angularjs i.e. you can publish an event somewhere and subscribe to it from other place.

    $emit:
    It will post event name upwards to the different scopes and then notify to $rootscope listeners. This event will start from the place where emit method is called and will traverse upward till the rootscope and along with calls the registered listeners.

    $broadcast:
    It will post event name downwards to the different scopes and then notify to $rootscope listeners. This event will start from the place where broadcast method is called and will traverse downwards till the child scopes and along with calls the registered listeners.

    If we need to communicate a service to directive, these method can be used.

    We can start an event ParentCtrl to childoneCtrl using $broadcast:

    <div ng-controller="ParentCtrl as parent" class="ng-scope">
      {{ parent.data }}
      <div ng-controller="SiblingOneCtrl as sib1" class="ng-scope">
          {{ sib1.data }}
      </div>
    </div>
    app.controller('ParentCtrl',
      function ParentCtrl ($scope) {
    
      $scope.$broadcast('parent', 'Some data'); // going down!
    
    });
    
    app.controller(childoneCtrl',
      function childoneCtrl ($scope) {
    
      $scope.$on('parent', function (event, data) {
        console.log(data); // 'Some data'
      });
    
    });

     

    To start an event upwards from childoneCtrl to ParentCtrl, you can use $emit:

    app.controller('ParentCtrl',
      function ParentCtrl ($scope) {
    
      $scope.$on('child', function (event, data) {
        console.log(data); // 'Some data'
      });
    
    });
    
    app.controller('childoneCtrl',
      function childoneCtrl ($scope) {
    
      $scope.$emit('child', 'Some data'); // going up!
    
    });

    When you bind to an event using the scope.$on() method, your event handler is called.(ie, broadcast vs emit).

    You can see the demo here.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: