Friday 20 November 2015

Inter controller communication in angularjs, Sharing the data between pages or angularjs controllers using $rootScope



Question : How can we share information between the two different angular controllers? 

Answer: Inter controller communication in Angularjs can be achieved using the following mechanisms.

1. Using the $rootScope
2. By Using one of the mechanism for creating the custom services in Angularjs.
    These are...
     a) Factory Method
     b) Value Method
     c) Service Method or
     d) Provide Method.

In this article we will use the factory method for inter controller communication in Angularjs

Problem Statement:

We have a List of available Stores in the UI. These list is made available from one controller "storeList".

There is another controller "storeInfo" which displays the store information.

Once the store is selected in the "storeList" controller the corresponding store information should be made available in the "storeInfo" controller which actually glues this information to the view.

Solution :

Code:
Selected Store is: {{selectedStore}}


Controllers
var storeApp = angular.module('storeApp',[])
storeApp.factory('currentCustomer',function($rootScope) {
  var currentCustomer =  {};
  currentCustomer.customerID = 0;
  currentCustomer.customerName = '';
      currentCustomer.getCustomers =  function () {
          return [{CustomerID:1,CustomerName:'Store 1'},
                  {CustomerID:2,CustomerName:'Store 2'},
                  {CustomerID:3,CustomerName:'Store 3'}]; 
      };
      currentCustomer.setCurrentCustomer = function (custObject) {
        this.customerID = custObject['CustomerID'];
        this.ustomerName = custObject['CustomerName'];
        this.publishChanges();
      }; 
      
      currentCustomer.getCustomerID = function(){
        return this.customerID;
      };
  
      currentCustomer.getCustomerName = function(){
        return this.customerName; 
      };      
      currentCustomer.publishChanges = function() {
              $rootScope.$broadcast('custDataChangeEvent');
      };
    return currentCustomer; 
});  
    

// controller storeList

    storeApp.controller('storeList',function($scope,$http,currentCustomer,$filter) {
      $scope.customers = currentCustomer.getCustomers();
      $scope.changeCust = function changeCust(id) {
          var filteredCustomerList = $filter('filter')($scope.customers,{CustomerID:id},true);
          var currCustomer = filteredCustomerList[0];
          currentCustomer.setCurrentCustomer(currCustomer);
      };
    });

      // listen to the events
      storeApp.controller('storeInfo',function($scope,currentCustomer) {
      $scope.$on('custDataChangeEvent',function(){
       $scope.selectedStore = currentCustomer.getCustomerID();
      });
});

Explanation:

All the Objects in AngularJs are singleton.

In this example currentCustomer is the factory service created.  The factory method returns the currentCustomer object consisting of the customerID and customerName attributes along with the necessary methods like
1. get customer List
2. get CustomerId and getCustomerName
3. set customer details.
4. and importantly a method "publishChanges" which actually notifies the updates made in the currentCustomer  object.

To publish the changes we used the $broadcast service provided by angular. Please check my post on the $broadcast and $emit and $on services.

I will be soon posting it.

storeList controller :

It retrieves the customer list from the factory method and keeps it in its controller scope.
Once the user selects the store from the select option the id is passed to the changeCust scope method. From the customer array which available in the controller, object is filtered using the id.  To filter a particular record from the array we have used the $filter service provided by angular.  Please have a look at my post on the filter.   I will be soon posting it.

The selected customer is then set as the current customer using the factory methods setCurrentCustomer

storeInfo controller:

This controller listens to the publish event. As soon as the customer details are updated. currentCustomer factory's publish method broadcasts the changes to all the controllers. The controllers which are listening to this event a callback function is called where we can take the appropriate action against this changes.

in our example we update the customerID information to the scope selectedStore which is glued back to the view.

There are other ways to achieve this. One way is to use the provider recipes like value or factory.
Please check another article http://yogeshtutorials.blogspot.in/2015/11/session-tracking-in-angularjs.html

Thanks.

3 comments:

  1. It was really a nice article and i was really impressed by reading this AngularJS Online Training Bangalore

    ReplyDelete
  2. Thanks for the useful blog
    Yaaron Studios is one of the rapidly growing editing studios in Hyderabad. We are the best Video Editing services in Hyderabad. We provides best graphic works like logo reveals, corporate presentation Etc. And also we gives the best Outdoor/Indoor shoots and Ad Making services.
    Best video editing services in Hyderabad,ameerpet
    Best Graphic Designing services in Hyderabad,ameerpet­
    Best Ad Making services in Hyderabad,ameerpet­

    ReplyDelete