Wednesday, December 30, 2015

The best way for sharing data between controllers in AngularJS 1.x

You may know the situation in AngularJS 1.x when multiple independent controllers need to share some data. E.g. one controller adds some data that should be available in the other controllers in the same view. So far as I know there are three possibilities:
  • Using $scope, e.g. $scope of a common parent controller or $rootScope
  • Using publish-subscribe design pattern via $emit / $broadcast (fire events) and $on (listen for events)
  • Using services which can be injected in multiple controllers.
The first possibility to share data via $scope is a bad idea. If you share data via scopes, you have to know controllers' parent-child relationship. That means, your controllers are tightly coupled and the refactoring is hard to master. Some AngularJS examples save the data on the $rootScope, but the pollution of $rootScope is not recommended. Keep the $rootScope as small as possible. The event based possibility to share data via $emit, $broadcast and $on is a better approach in comparison to scope based one. The controllers are loosely coupled. But there is a disadvantage as well - the performance. The performance is ok for a small application, but for a large application with hundreds of $on listeners, the AngularJS has to introspect all scopes in order to find the $on listeners that fit to the corresponsing $emit / $broadcast. From the architecture point there is a shortcoming as well - we still need scopes to register $emit, $broadcast and $on. Some people also say - communication details should be hidden for the same reason we keep $http hidden behind a service layer. There are 5 guidelines for avoiding scope soup in AngularJS. The last 5. rule is called Don't Use Scope To Pass Data Around. It advices against using scopes directly and against event based approach. Last but not least - think about the upcomming AngularJS 2. It doesn't have scopes!

In my opinion, the preferred way for sharing data between controllers in AngularJS 1.x is the third possibility. We can use services. A service can keep data or acts as event emitter (example is shown below). Any service can be injected into controllers, so that conrollers still don't know from each other and thus are loosely coupled. I will refactor and extend one example from this blog post. The author of this blog post implemented two controllers for two panes. In the left pane we can input some text and add it as an item to a list in the right pane. The list itself is placed in a service (service encapsulates the data). This is probably a good idea when you have different views or controllers in conditional ng-if. But if controllers exist in the same view and show their data at the same time, the list should reside in the controller for the right pane and not in the service. The list belongs to the second controller. This is my opinion, so I will move the list into the controller and also add a third "message controller" which is responsible for messages when user adds items to the list or removes them from the list. We thus have three controllers and one service. The idea is to apply the listener pattern (also known as observer) to the service. The service acts as event emitter. Every controller can fire an ADD or REMOVE operation and register a listener function to be notified when the operation is done. The added / removed item acts as data passed along with operation into all registered listeners for the given operation. The live example is implemented on Plunker.

The first picture shows the adding process (click on the button Add To List) with a message about the successfully added item.


The second picture shows the removing process (click on a link with x symbol) with a message about the successfully removed item.


The HTML part looks as follows:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta content="IE=edge" http-equiv="X-UA-Compatible" />
    <script src="https://code.angularjs.org/1.4.8/angular.js"></script>
</head>

<body ng-app="app">
    <div ng-controller="MessageController as ctrlMessage" style="margin-bottom:20px;">
        <span ng-bind-html="ctrlMessage.message"></span>
    </div>

    <div ng-controller="PaneOneController as ctrlPaneOne">
        <input ng-model="ctrlPaneOne.item">
        <button ng-click="ctrlPaneOne.addItem(ctrlPaneOne.item)">Add To List</button>
    </div>

    <div ng-controller="PaneTwoController as ctrlPaneTwo" style="float:right; width:50%; margin-top:-20px;">
        <ul style="margin-top:0">
            <li ng-repeat="item in ctrlPaneTwo.list track by $index">
                {{item}}
                <a href style="margin-left:5px;" title="Remove" ng-click="ctrlPaneTwo.removeItem($index)">x</a>
            </li>
        </ul>
    </div>

    <script src="controller.js"></script>
    <script src="service.js"></script>
</body>
</html>
As you can see, there are three independent HTML div elements with ng-controller directive. The MessageController shows a message above. The PaneOneController keeps an input value and the function addItem(). The PaneTwoController keeps a list with all items and the function removeItem(). The controllers look as follows in details:
(function() {
    var app = angular.module('app', []);
    app.controller('PaneOneController', PaneOneController);
    app.controller('PaneTwoController', PaneTwoController);
    app.controller('MessageController', MessageController);

    /* first controller */
    function PaneOneController(EventEmitterListService) {
        var _self = this;
        this.item = null;

        this.addItem = function(item) {
            EventEmitterListService.emitAddItem(item);
            _self.item = null;
        }
    }

    /* second controller */
    function PaneTwoController($scope, EventEmitterListService) {
        var _self = this;
        this.list = [];

        this.removeItem = function(index) {
            var removed = _self.list.splice(index, 1);
            EventEmitterListService.emitRemoveItem(removed[0]);
        }

        EventEmitterListService.onAddItem('PaneTwo', function(item) {
            _self.list.push(item);
        });

        $scope.$on("$destroy", function() {
            EventEmitterListService.clear('PaneTwo');
        });
    }

    /* third controller */
    function MessageController($scope, $sce, EventEmitterListService) {
        var _self = this;
        this.message = null;

        EventEmitterListService.onAddItem('Message', function(item) {
            _self.message = $sce.trustAsHtml("<strong>" + item + "</strong> has been added successfully");
        });

        EventEmitterListService.onRemoveItem('Message', function(item) {
            _self.message = $sce.trustAsHtml("<strong>" + item + "</strong> has been removed successfully");
        });

        $scope.$on("$destroy", function() {
            EventEmitterListService.clear('Message');
        });
    }
})();
All three controllers communicate with a service called EventEmitterListService. The service exposes three methods:
  • emitAddItem - notifies listeners that are interested in adding an item to the list. The item is passed as parameter.
  • emitRemoveItem - notifies listeners that are interested in removing an item from the list. The item is passed as parameter.
  • onAddItem - registers a listener function that is interested in adding an item to the list. The listener is passed as parameter.
  • onRemoveItem - registers a listener function that is interested in removing an item from the list. The listener is passed as parameter.
  • clear - removes all registered listeners which belong to the specified controller. The controller is identified by the scope parameter (simple unique string).
The clear method is important when the $scope gets destroyed (e.g. when the DOM associated with the $scope gets removed due to ng-if or view switching). This method should be invoked on $destroy event - see code snippets with $scope.$on("$destroy", function() {...}). The full code of the service is listed below:
(function() {
    var app = angular.module('app');
    app.factory('EventEmitterListService', EventEmitterListService);

    function EventEmitterListService() {
        // Format of any object in the array:
        // {scope: ..., add: [...], remove: [...]}
        // "scope": some identifier, e.g. it can be the part of controller's name
        // "add": array of listeners for the given scope to be notified when an item is added
        // "remove": array of listeners for the given scope to be notified when an item is removed
        var listeners = [];

        function emitAddItem(item) {
            emitAction('add', item);
        }

        function onAddItem(scope, listener) {
            onAction('add', scope, listener);
        }

        function emitRemoveItem(item) {
            emitAction('remove', item);
        }

        function onRemoveItem(scope, listener) {
            onAction('remove', scope, listener);
        }

        function clear(scope) {
            var index = findIndex(scope);
            if (index > -1) {
                listeners.splice(index, 1);
            }
        }

        function emitAction(action, item) {
            listeners.forEach(function(obj) {
                obj[action].forEach(function(listener) {
                    listener(item);
                });
            });
        }

        function onAction(action, scope, listener) {
            var index = findIndex(scope);
            if (index > -1) {
                listeners[index][action].push(listener);
            } else {
                var obj = {
                    'scope': scope,
                    'add': action == 'add' ? [listener] : [],
                    'remove': action == 'remove' ? [listener] : []
                }
                listeners.push(obj);
            }
        }

        function findIndex(scope) {
            var index = -1;
            for (var i = 0; i < listeners.length; i++) {
                if (listeners[i].scope == scope) {
                    index = i;
                    break;
                }
            }

            return index;
        }

        var service = {
            emitAddItem: emitAddItem,
            onAddItem: onAddItem,
            emitRemoveItem: emitRemoveItem,
            onRemoveItem: onRemoveItem,
            clear: clear
        };

        return service;
    }
})();
That's all. Happy New Year!

2 comments:

  1. Very informative blog. I was searching for something like this. your blog helped me a lot. Thank you so much for sharing. Its really worth to visit this blog. Website Design Fort Lauderdale

    ReplyDelete

Note: Only a member of this blog may post a comment.