Saturday, April 26, 2014

AngularJs Pass Data Between Controllers

Hello,

This is my first blog on AngularJs. I have been working with AngularJs since last three or four weeks and I am very excited about this Framework. It has nice features like two way data binding, templates, MVVM model, directives. That makes this framework super cool. I will be adding more blogs in future for AngularJs. In this blog I will explain how to pass data between controllers.

For this first we have to understand $rootScope. Every AngularJs application has one root scope and all other scopes are children of root scope. It's like application wide global variable.

Now lets see how we can use this to share data between controllers. First we need a service which is common in both controllers. We will invoke a service function from a controller which wants to send data. Service will broadcast it and using $rootScope. While the receiver controller will listen to the broadcast event and receives that data. First lets crete a service and function.

var servicesModule = angular.module('myapp.broadcastservice', []);

servicesModule.factory('BroadcastService', ['$http', '$rootScope', function ($http, $rootScope) {

   var service = {};
   service.sendData = function(data){

      $rootScope.$broadcast('message', data);
   }

}

Now lets create sender controller.

appRoot.controller('SenderController', ['$scope', 'BroadcastService',
   function ($scope, BroadcastService) {
        $scope.sendData = function(){
              BroadcastService.sendData("My Message");
        }
   }
]);

Now lets create a receiver controller

appRoot.controller('ReceiverController', ['$scope', 'BroadcastService',
    function ($scope, BroadcastService) {
        $scope.$on('message', function(response, data) {
            console.log(data);
       });
    }
]);

As you can see from sender controller we invoke service function and broadcast message with event message and in receiver controller we receive it by listening to message event using $scope.$on.

This way you can pass data between AngularJs controllers. Hope this post helps you.   

No comments:

Post a Comment