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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.53k
    Comment on it

    Sometimes we need to send data from one controller to another. There are services provided by AngularJS for communication(event-based) between the controllers. $on, $emit, $broadcast are the services for the communication between the controllers.

    $on :- $on is used to catch the event dispatched by $broadcast and $emit. Basically it’s a method of scope and listens on events of a given type.

    $broadcast : - $broadcast is the service that dispatches an event downwards to the child scopes. The life cycle of the event starts at the scope where the $broadcast is called. For example :-
     

    app.controller(Eg1ctrl, function ($scope) {
     $scope.$broadcast('eventName', { Tips: tip });
     });
     
     app.controller("Eg2ctrl", function ($scope) {
     $scope.$on('eventName', function (event, args) {
     $scope. Tips = args. Tips;
     console.log($scope. Tips);
     });
     });

       If scope of Eg1ctrl is parent of the Eg2ctrl scope, it should work by using $broadcast in Eg1ctrl. This event cannot be cancelled.

    $emit :- $emit is the service that dispatches an event upwards to the parent scopes. The life cycle of the event starts at the scope where the $emit is called. All the listeners along the way gets notified. For example :-

     app.controller("Eg1ctrl", function ($scope) {
     $scope.$on('eventName', function (event, args) {
     $scope.Tips = args.Tips;
     console.log($scope.Tips);
     });
     });
     
     app.controller("Eg2ctrl", function ($scope) {
      $scope.$emit('eventName', { Tips: tip });
     });

    If scope of Eg1ctrl is parent of the Eg2ctrl scope, it should work by using $emit in Eg2ctrl. This event stops moving if one of the listeners cancels it .

     

 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: