Sunday, August 10, 2014

Communication between controllers in AngularJS

In this article we will learn to communicate between controllers in AngularJS.  We know that AngularJS gives MVC architecture in client side and gives compete separation of business logic, presentation logic and data.
We know that Controller section is responsible to execute business logic and act as glue between view and model. In application development it’s often necessary to exchange data between controllers to maintain consistent data throughout application.

To share data among controller we will use concept of service in application and both the controller will consume service. In this example service will perform as repository.

So, let’s try to implement in code. At first we will implement the client page and then we will implement code in Angular.

<html ng-app="myApp">
        <script src="angular.min.js" type="text/javascript"></script>
        <script src="Dependency.js" type="text/javascript"></script>
        <div ng-controller="SetController">
                <td>Enter Name</td>
                <td> <input type="text" name="text" ng-model="personName" /> </td>
                <td colspan="2">
                    <input type="button" name="Add" value="Add" ng-click="add()" />

        <div ng-controller="GetController">
            <input type="button" name="Show" value="Show All" ng-model="show" ng-click="show()" />


Implement service and controller in Angular

Now, we will implement service and controllers in AngularJS. Have a look one below code.

var app = angular.module('myApp', []);
app.service('dataService', function () {
    var data = [];

    var push = function (object) {

    var pull = function () {
        return data;

    return {
        push: push,


app.controller('SetController', ['$scope' ,'dataService', function ($scope, dataService) {
    $scope.add = function () {
        var person = new Object(); = $scope.personName;


app.controller('GetController', ['$scope','dataService' , function ($scope,dataService) {
    $ = function () {
        var data = dataService.pull();

So, we have defined module at first and then attached ‘dataService’ service to the module. GetController and SetController are two controllers which are communicating to the ‘dataService’ service.
As both controllers are talking to same service, so that the service will contain updated data and controller as subscribe can able to share data across it.
Let’s run the application. Enter some text in textbox and press add button, once we press add it will save data to service.

Now, press ShowAll button and it will get data from service. Now , please note that data is sharing between two controllers.  

Border line:
In this article we have learned to implement share data across controller using service.  This is one simplest process to share data in controllers though there are many more. 

No comments:

Post a Comment