Communication Strategies in AngularJS 1.x

As the application scales in size, controlling communication between components requires enough thought to ensure there isn’t too much or too little of it. In this post we will look at the various ways of communicating in AngularJS 1.x. Some of these techniques may still apply in the Angular 2 world (eg: Events), however the actual mechanics will be different.

The different ways of communication

AngularJS 1.x offers several ways of communicating between components. These are based on the core abstractions that Angular provides, namely: Services, Directives, Controllers and of course the Scope.

Below, we explore these alternatives with some simple examples.

Communicating via Scope

Data binding was the pivotal feature of Angular that got its initial popularity. By having a scope (the model) bound to a template you are able to replace placeholder mustache-like strings {{ model.prop }} with their actual values from the scope (aka model). This way of expanding templates to build pages is very convenient and productive. Here, Scope acts as the binding glue to fill in values for the mustache-strings. At the same time, scope also has references to event-handlers that can be invoked by interacting with the DOM.

Note that these placeholders automatically create a two-way binding between the model and the DOM. This is possible, as you already know, via the watchers. Also worth mentioning is that with Angular 1.3, you can create one-time bindings with {{ ::model.prop }} syntax. Make sure you put the ::.

The example below shows the controller and its usage in the template. The key part here is the use of scope (the binding glue) to read model values as well provide interaction.

1 angular.module('exemplar')
2     .controller('MidLevelController', function ($scope) {
4         $scope.midLevelLabel = 'Call Mid Level';
5         $scope.midLevelMethod = function () {
6             console.log('Mid Level called');
7         };
8     });
1     <div class="panel mid-level" ng-controller="MidLevelController">
2         Mid Level Panel
4         <div class="panel bottom-level">
5             <button ng-click="callMidLevelMethod()">{{ midLevelLabel }}</button>
6         </div>
7     </div>

Communicating implicitly via the Prototypical Scope

Scopes in Angular directives (and Controllers) prototypically inherit from the parent scopes. This means a child-directive (or Controller) is able to reference and use properties of its parent scope just by knowing the properties. Although not a recommended approach, this can work well for simple directives that are not using Isolate Scopes. Here there is an implicit contract between the parent and child directives (or Controllers) to share a few properties.

In the example below, you can see that the BottomLevelController is able to invoke a method on the TopLevelController purely because of the prototypical scope.

 1 <div class="panel top-level" ng-controller="TopLevelController">
 2     Top Level Panel
 3     <div class="panel mid-level" ng-controller="MidLevelController">
 4         Mid Level Panel
 6         <div class="panel bottom-level" ng-controller="BottomLevelController">
 7             <button ng-click="callMidLevelMethod()">{{ midLevelLabel }}</button>
 8             <button ng-click="topLevelMethod('Bottom Level')">Call Top Level</button>
 9         </div>
10     </div>
11 </div>

And here are the controllers:

 1 angular.module('exemplar')
 2     .controller('TopLevelController', function ($scope) {
 4         $scope.topLevelMethod = function (sender) {
 5             console.log('Top Level called by : ' + sender);
 6         };
 7     })
 8     .controller('MidLevelController', function ($scope) {
10         $scope.midLevelLabel = 'Call Mid Level';
11         $scope.midLevelMethod = function (sender) {
12             console.log('Mid Level called by: ' + sender);
13         };
14     })
15     .controller('BottomLevelController', function ($scope) {
17         $scope.callMidLevelMethod = function () {
18             $scope.midLevelMethod('bottom-level');
19         };
20     });

Communicating via Controllers

When there is a natural, nested relationship with directives, it is possible to communicate between them by having the child depend on the parent’s Controller. This is generally done within the child-directive by providing a link() function and a dependency on the parent directive’s controller. The dependency is established using the require attribute of the child’s directive-definition-object. You can even depend on more controllers from the parent chain by using the array syntax. They all show up as the fourth parameter in the link() function. {” Note, for this to work, the parent-directive must have a Controller defined. “}

Consider the example below where we have nested directive structure:

1 <parent-component>
2     <child-component></child-component>
3 </parent-component>

Here we can wire the <child-component> and <parent-component> with the following directives. Note line#23 where we require the parent controller and line#25 where we take in the instance in the link function.

 1 angular.module('exemplar')
 2     .directive('parentComponent', function () {
 4         return {
 5             restrict: 'E',
 6             templateUrl: 'parent-child-directive/parent-component.template.html',
 7             transclude: true,
 8             controller: ParentComponentController
 9         };
11         function ParentComponentController($scope) {
13             var vm = this;
14             vm.takeAction = function () {
15                 console.log('The <child-component> called me');
16             }
17         }
18     })
19     .directive('childComponent', function () {
21         return {
22             restrict: 'E',
23             require: '^parentComponent',
24             templateUrl: 'parent-child-directive/child-component.template.html',
25             link: function (scope, element, attrs, parentController) {
27                 scope.notifyParent = function () {
28                     parentController.takeAction();
29                 }
30             }
31         }
32     });

Communicating via Services

Services are the singletons of Angular that are used to capture behavior. However by the virtue of being singletons, they also act as shared storage and can be used to aid communication between disparate components (Directives). The communicating parties depend on the shared service and use the methods on the service to do the communication.

In the example below, you can see a simple clipboardService that provides a shared storage for the copyButton and pasteButton directives.

 1 (function () {
 2     angular.module('exemplar')
 3         .factory('clipboardService', serviceFunction);
 5     function serviceFunction() {
 7         var clipboard = {};
 9         return {
10             copy: function (data, key) { /* ... */ },
11             get: function (key) { /* ... */ }
12         };
13     }
14 })();
 1 angular.module('exemplar')
 2     .directive('copyButton', function (clipboardService) {
 4         return {
 5             restrict: 'A',
 6             link: function (scope) {
 8                 scope.performCopy = function () {
 9                     // Invoke Copy
10                     clipboardService.copy({}, 'abc');
11                 };
12             }
13         };
14     })
15     .directive('pasteButton', function (clipboardService) {
17         return {
18             restrict: 'A',
19             link: function (scope) {
21                 scope.performPaste = function () {
22                     // Fetch from clipboard
23                     var data = clipboardService.get('abc');
25                     /* ... Handle the clipboard data ... */
26                 };
27             }
28         };
29     });

Communicating via Events

Events are the cornerstones of all UI Frameworks (or any event-driven framework). Angular gives you two ways to communicate up and down the UI tree. Communicate with parents or ancestors via $emit(). Talk to children or descendants via $broadcast().

As an extension, you can talk to every component in the app via $rootScope.$broadcast(). This is a great way to relay global events.

On the other hand, a more focused $rootScope.$emit() is useful for directed communication. Here $rootScope acts like a shared service. Communicating with events is more like message-passing where you establish the event-strings and the corresponding data that you want to send with that event. With the right protocol (using some event-string convention) you can open up a bi-directional channel to communicate up and down the UI tree.

In the example below, you can see two controllers (DeepChildController and RootController) which communicate using the $rootScope. With $rootScope, you get a built-in shared service to allow any child component to communicate with the root.

 1 angular.module('exemplar')
 2     .controller('DeepChildController', function ($scope, $rootScope) {
 4         $scope.notifyOnRoot = function () {
 5             $rootScope.$emit('app.action', {name: 'deep-child'});
 6         };
 7     })
 8     .controller('RootController', function ($scope, $rootScope) {
10         $rootScope.$on('app.action', function (event, args) {
11             console.log('Received app.action from: ',;
12         });
13     });
 1     <div class="root" ng-controller="RootController">
 2     <!-- Some where deep inside the bowels of the app -->
 3         <ul>
 4             <li>One</li>
 5             <li>Two</li>
 6             <li ng-controller="DeepChildController">Three has
 7                 <button ng-click="notifyOnRoot()">Talk to Root</button>
 8             </li>
 9         </ul>
10     </div>

Communication outside Angular

Although you may be using Angular, you are not limited to doing everything the angular way. You can even have side communication outside of Angular using a shared bus from the PubSub model. You could also use WebWorkers for running intensive operations and showing the results via Angular.

The catch here is that once you want to display results on the DOM, you will have to enter the Angular context. This is easily done with a call to $rootScope.apply() at some point where you obtain the results.

Now the question is how do you get the $rootScope outside of angular. Well, below is the snippet. Here we are assuming your ng-app is rooted on document.body.

1 // Get $rootScope
2 var rootScope = angular.element(document.body).injector().get('$rootScope');
4 // Trigger a $digest
5 rootScope.$apply(function(){
6     // Set scope variables for DOM update
7 });

Performance Gotchas in communication

Communicating at scale (inside your app) comes with a few gotchas and can seriously affect performance. For example, if you are listening to a streaming server that is pumping market data every second, you may be running $scope.$digest() or $rootScope.$digest() every second!. You can imagine the turmoil it will cause in terms of performance. End result: An ultra-sluggish app.

One of the most popular techniques to handle high volume communication is to debounce the handler. This ensures that the actual event is only handled once in a defined time interval. So for the duration of the interval, events are ignored. Debouncing can be introduced at various places in your data-pipeline to control the burst of events.

Note: If you don’t want to ignore the data in an event, you can buffer it for use at the end of the interval. In general, batching is universal for controlling volume. It is much more efficient to combine several small activities into one batched-activity.

In Summary

Communication within an application, just like building software, is a mixture of Art + Science. The science part is the mechanics of communication, many of which we have seen above. The art is knowing when to employ the right one! Using the right methods can make a big difference to the maintainability, stability and overall performance of your application.

Although we have used Angular as a pretext to discuss these communication styles, many of them are universal and apply to any JavaScript application. I’ll leave it as an exercise for you to map to your own favorite framework.

Question: Have I missed out any particular technique here? Something that you have used effectively? Please do share in comments.