Search code examples
angularjsasp.net-mvcmaster-pages

angularjs using $on and $broadcast to communicate between a master controller to another controller


I am trying to set communication between two angular controllers (service is not an option). and I am failing desperately.

here is some of my code... i tried using both $emit and $broadcast

invoiceApp.controller('masterReportConrtoller', ['$scope', '$location', 'authService', 'usSpinnerService', 'dateService', 'settingsService','$rootScope',
function ($scope, $location, authService, usSpinnerService, dateService, settingsService, $rootScope ) 
 ////Is User Valid
    ////
    //$rootScope.$on("masterReportConrtoller", function () {
    //        $scope.parentmethod();
    //    });
    //$scope.parentmethod = function () {
    //    //
    $scope.masterReportConrtoller.getUserDetails = function () {
        debugger;
            settingsService.getUserDetails().then(function (response) {
                var loginData = {
                    userName: response.d.user.Email,
                    password: response.d.user.UserPassword

                };
            authService.login(loginData).then(function (response) {
                debugger;
                $scope.Limit = response.d.organization.Limit;
            });
            $scope.Limit = response.d.organization.Limit;
            $scope.DocumentUsage = response.d.organization.DocumentUsage;
            $scope.ExpirationDate = $scope.DateConvertfromJson(response.d.organization.ExpirationDate);
            var fullDate = new Date();
            if (fullDate <= $scope.ExpirationDate) {
                $scope.ISvalidUser = false;
                $rootScope.$broadcast('masterReportConrtoller', false);
            }
            else {
                $rootScope.$broadcast('masterReportConrtoller', true);
            }
        });
    }   
}]);


invoiceApp.controller('InvoiceController', ['$scope', '$location', '$cookieStore', 'documentService', 'dialogs', 'usSpinnerService', 'settingsService', 'associatedEmailsService', '$rootScope',
function ($scope, $location, $cookieStore, documentService, dialogs, usSpinnerService, settingsService, associatedEmailsService, $rootScope) {


 $rootScope.$on('masterReportConrtoller');}

Solution

  • Based on your parent - child controller relationship, you can use $scope.$broadcast and $scope.$on in your code.

    Try something like this:

    //masterReportConrtoller
    $scope.$broadcast("myCustomEvent", { isValidUser: false });
    
    //InvoiceController
    $scope.$on("myCustomEvent" , function(event, data){
       //do something with data
    });
    

    Please note that this will work if masterReportConrtoller is the parent controller and InvoiceController is the child controller. If this is not the case, then use $rootScope.$broadcast and $rootScope.$on.

    You can find more details here.