Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Communication between the Controllers in AngularJS

4.30/5 (8 votes)
14 May 2014CPOL3 min read 47.6K  
AngularJS: Communication between Controllers

What is AngularJS?

AngularJS is a JavaScript framework for creating Single Page Application. A framework implies that instead of writing code however you want, you change the way in which you write your applications and follow the standards set by the framework. By doing this, you can take advantage of built in features of AngularJS like two way data binding, templating, filters, etc. You do things in a certain way and that gives you super powers.

AngularJS is designed to build single page applications that means regardless of the size of your application, your browser is going to load single page while additional contents will be loaded as needed. In a way, this will be a faster way to create applications. It contains lot of features which may take lot of time if you want to implement by yourself.

Features of AngularJS

It is a very good Templating Engine. It handles Document object model (DOM) more efficiently. Template is automatically populated with data. We can do data manipulation very easily including AJAX functionality. We can load JSON data easily.

It uses object oriented approach for programming. It is built on Model View Controller (MVC ) architecture. We can use this approach to accomplish our goals.

  1. Model: M stands for Model. The data or the state represented by the web application or to be specific, the state of the concerned web page.
  2. View: The visual representation of model. Its responsibility is to present the information in model in a user appreciable format.
  3. Controller: The brain dictating the application behavior. Its responsibility is to link the right model with the right view, act as glue between data and View.

AngularJS also uses Directives which are nothing more than commands throughout the HTML which tell AngularJS to do the job.

Data binding helps for templating. You can bind model and view.

Filters help you to organize the data in a certain way.

Modules help to break the functionality into modules which are easy to maintain.

Routes which help to link the information with different views help you to decide the sequence to show the information dynamically depending on events.

Controllers decide how the events can be handled. Functionality for each view can be handled by different controllers.

Scope

Sharing the information between different pages is a critical task which can be done with the help of Controllers.

In AngularJS, we can share the data between controllers in three ways:

  1. Factory: Object is created inside the factory and return it .
  2. Service: With the service, you just have a standard function that uses the this keyword to define function.
  3. Provider: With the provider, there’s a $get you define and it can be used to get the object that returns the data.

In this article, we are going to consider how we can share the data between two controllers using factory method .

Code Sample

HTML Code

XML
<div ng-controller="FirstController">
    <input ng-model="sharedmessage" >
    <button ng-click="publishClick(sharedmessage);">LOG</button>
</div>
<div ng-controller="SecondController">
    <input ng-model=" sharedmessage " >
</div>
<div ng-controller="ThirdController">
    <input ng-model=" sharedmessage " >
</div>

App.js (JavaScript Code)

PHP
var demoModule = angular.module('demoModule', []);
demoModule.factory(mySharedService, function($rootScope) {
    var sharedService = {};

    sharedService.sharedmessage  = '';

    sharedService.prepForPublish = function(msg) {
        this.sharedmessage  = msg;
        this.publishItem();
    };

    sharedService.publishItem = function() {
        $rootScope.$broadcast('handlePublish');
    };

    return sharedService;
});

function FirstController($scope, sharedService) {
    $scope.publishClick = function(msg) {
        sharedService.prepForPublish(msg);
    };

    $scope.$on('handlePublish', function() {
        $scope.sharedmessage  = sharedService.sharedmessage ;
    });
}

function SecondController($scope, sharedService) {
    $scope.$on('handlePublish', function() {
        $scope.sharedmessage  = SecondController : ' + sharedService.sharedmessage ;
    });
}

function ThirdController($scope, sharedService) {
    $scope.$on('handlePublish', function() {
        $scope.sharedmessage  = 'ThirdController: ' + sharedService.sharedmessage ;
    });
}

FirstController.$inject = ['$scope', mySharedService];

SecondController.$inject = ['$scope', mySharedService];

ThirdController.$inject = ['$scope', mySharedService];

Code Description

In the HTML screen, we saw that we have three DIVs and each DIV is different Controllers. Each DIV contains one text box. Each input box contains are bind to sharedmessage.

XML
<div ng-controller="FirstController">
    <input ng-model="sharedmessage" >
    <button ng-click="publishClick(sharedmessage);">LOG</button>
</div>
<div ng-controller="SecondController">
    <input ng-model=" sharedmessage " >
</div>
<div ng-controller="ThirdController">
    <input ng-model=" sharedmessage " >
</div>

Create the module as demoModule and create service named as mySharedService.

C#
var demoModule = angular.module('demoModule', []);
demoModule.factory(mySharedService, function($rootScope) {

We have two functions, one is "prepForPublish" and "publishItem" .

C#
var sharedService = {};

sharedService.sharedmessage  = '';

sharedService.prepForPublish = function(msg) {
    this.sharedmessage  = msg;
    this.publishItem();
};

sharedService.publishItem = function() {
    $rootScope.$broadcast('handlePublish');
};

return sharedService;

When any input is typed in the first input box, for example" ABC" and LOG button is clicked, the contents will come with sharemessage variable, then it will call prepForPublish function. This will publish the contents.

First Controller will take input and update the shared variable:

PHP
function FirstController($scope, sharedService) {
    $scope.publishClick = function(msg) {
        sharedService.prepForPublish(msg);
    };

    $scope.$on('handlePublish', function() {
        $scope.sharedmessage  = sharedService.sharedmessage ;
    });
}

Second Controller will get the updated value:

PHP
function SecondController($scope, sharedService) {
    $scope.$on('handlePublish', function() {
        $scope.sharedmessage  = SecondController : ' + sharedService.sharedmessage ;
    });
}

Similarly third controller will get the updated value:

PHP
function ThirdController($scope, sharedService) {
    $scope.$on('handlePublish', function() {
        $scope.sharedmessage  = 'ThirdController: ' + sharedService.sharedmessage ;
    });
}

As mySharedService is injected in three controllers:

C#
FirstController.$inject = ['$scope', mySharedService];

SecondController.$inject = ['$scope', mySharedService];

ThirdController.$inject = ['$scope', mySharedService];

As shown in the first screen, when ABC is typed in the first textbox, it will reflect in the second and third box using two controllers. In this way, we can share the information between three controllers using factory method. As generally each page has its own controller, we can pass the information between different pages.

Conclusion

We can conclude that we can share the data between two controllers in AngularJS using factory method. This is a simple way and is easy to implement.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)