Broadcast Fun

angular_js Have you ever come across the need to call a method in a child controller from a parent controller? That breaks all the rules right? Well maybe. Let’s find out if this is indeed possible. The AngularJS framework gives us an out here. We will use the $scope.$broadcast(name, args); method in the parent controller to send a message downwards to all child scopes (and their children, and their children’s children, etc.) When an event is broadcast down all of the listeners, it propagates to those listening with the $on(name, listener); method.

Let’s take a look at the HTML code for the page.

<!--DOCTYPE html>
<html>
<head>
    <title>Broadcast Fun</title>
</head>
<body ng-app="broadcastFunModule">
  <div ng-controller="parentCtrl">
    Parent Controller: {{ info }}
    <button ng-click="clickHandler()">Click Me</button>
    <div ng-controller="childCtrl">
      Child Controller: >em<{{ info }}</em>
    </div>
  </div>

  <script type="text/javascript" src="components/angular/angular.min.js"></script>
  <script type="text/javascript" src="scripts/app.js"></script>
</body>
</html>

As you can see we don’t have that much code here. That’s alright we just need enough for a demonstration here, I’ll let you learn how to apply this to your specific situation. Now that we’ve seen the front end, let’s take a look at the JavaScript code file app.js.

angular.module('broadcastFunModule', [])
  .controller('parentCtrl', ['$scope', function (scope) {
    scope.info = 'Information From Parent Controller';

    scope.childClickHandler = null;

    scope.clickHandler = function() {
      console.log('about to broadcast event');
      scope.$broadcast('childEvent');
      console.log('about to return the parent scope click handler');
      return scope.childClickHandler;
    };

    scope.$on('childEventPingBack', function(e, func) {
      console.log('Just received ping back, assigning the function');
      scope.childClickHandler = func;
      console.log('about to execute the function');
      func();
    });
  }])
  .controller('childCtrl', ['$scope', function(scope) {
    scope.info = 'Information From Child Controller';

    scope.$on('childEvent', function(e) {
      console.log('recieved the event, about to emit the click handler method.');
      scope.$emit('childEventPingBack', scope.clickHandler);
      console.log('just emitted the child scope click handler method.');
    });

    scope.clickHandler = function() {
      console.log('ALERT: This is the child click handler!');
    };
  }]);

Now once you’ve entered all that you are ready to save this and look at it in the browser. Here is the output that you should expect.
broadcast_output

As you can see from the output written to the console, we have the following things happen:

  1. about to broadcast event
  2. received the event, about to emit the click handler method.
  3. Just received ping back, assigning the function
  4. about to execute the function
  5. ALERT: This is the child click handler!
  6. just emitted the child scope click handler method
  7. about to return the parent scope click handler

This order gives us insight into what is happening during the event cycle. Note that the ALERT comes in before the just emitted the child scope click handler method. This gives us a clue that the emit itself is not asynchronous. This may not be the way that you are used to dealing with events. If you have blocking code in the method that wrote ALERT: This is the child click handler! to the console, you may have other consequences to deal with once you’ve freed the blocking code

That’s all for tonight. I hope that you learned something, I know I did! I love being able to explore a new area of the AngularJS framework. I hope that I’ve shed some light on not only what these methods do but how they interact with the event cycle as well. I hope to see you back here in the future for some more Angular Fun!

What me to write more about Angular? Add a nice comment below and let me know. Until then, Cheers!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s