Angular.js share variables between controllers with service

Note: This article applies to Angular 1 and the example is written in ES5.

Let’s say you have a directive where you have a button and once clicked you want an event to happen in another directive. The problem is that the two directives have different scopes, so passing the change directly is not possible. In this approach, we are going to use a service to pass the data between the controllers of the two directives.

For example, we are going to take a directive that has a button that once clicked we display a custom modal. The modal is another directive not related to the one where the click originated.

First, we are going to write the service:

"use strict";

angular.module("someApp").service("dataService", function () {

    var _isModalClicked  = false;

    this.setModalClicked = function(flag){
        _isModalClicked = flag;
    };

    this.getModalClicked = function(){
        return _isModalClicked;
    };
});

Then, from the controller sending the change (the one attached to button directive), we are going to set the variable on the service (don’t forget to import the service into the controller):

...
$scope.buttonClick = function(ev){
    dataService.setModalClicked(true);
}
...

At this point, we have wired the controller to the service and changed the state of _isModalClicked to true. What is left is to listen to that change inside of the controller consuming the event and to propagate the change, leading to showing the modal. The consuming controller will look like this:

'use strict';

angular.module('someApp')
    .controller('modalCtrl', function ($scope, dataService) {

        $scope.$watch(function() { return dataService.getModalClicked(); }, function(newVal) {
            $scope.showModal = newVal;
        }, true);
    });

This way, you have a clear separation of concerns when you want to pass a variable change between scopes.

Leave a Reply

Your email address will not be published. Required fields are marked *