Monday, March 27, 2017

AngularJS: Share data across multiple Controller instances with Controller As Syntax

In this article we are going to discuss how to share data across multiple controller instances.

We are going to use service to share the data. Service in Angular follows Singleton pattern.


Once it is initialized, it will have only one object.

Now let's have a look at the code:

First let's look at the Service:

var sharedDataService = app.service('ShareDataService',ShareData);

function ShareData(){
  var shareDataService = this;
    
  shareDataService.searchQuery = "";
  
  shareDataService.getSearchQuery = function(){
 return shareDataService.searchQuery;
  }
  
  shareDataService.setSearchQuery = function(searchQuery){
 shareDataService.searchQuery = searchQuery;
  }
}

As we can see the service has one setter and one getter. 

Now let's define the module and the controller.

We have only one controller, and we inject the service in that controller.

var app = angular.module('app', []);

var appCtrl = app.controller('AppCtrl', AppCtrl);

appCtrl.$inject = ['ShareDataService'];

function AppCtrl(ShareDataService){
  var appCtrl = this;
  appCtrl.variable = "search";
 
   appCtrl.setSearchQuery = function () {    
       ShareDataService.setSearchQuery(appCtrl.variable);
    }
     
 appCtrl.getSearchQuery = function () {    
        return ShareDataService.getSearchQuery();
    } 
 
}

When we get the data, we first set the data in the service instance and then try to reprieve the data.

After all this is done let's look at the html code:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app = "app">
  <div ng-controller = "AppCtrl as ctrl1">
     {{ctrl1.getSearchQuery()}}
  </div>
  <div ng-controller = "AppCtrl as ctrl2">
    <input type="search" ng-model = "ctrl2.variable" ng-change="ctrl2.setSearchQuery()"/>
     {{ctrl2.variable}}
  </div>
</div>

Hope this is clear to you, if not just post a comment.

No comments:

Post a Comment