Search code examples
javascriptangularjsangular-controller

how to send value of variable from ajax to another controllers


here is my controller:

.controller('loginCtrl', ['$scope',  '$window', '$cookies', '$http', function($scope, $window, $cookies, $http) {
    var frm = $('#loginForm');
    frm.submit(function(ev) {
        var now = new Date();
        now.setTime(now.getTime() + (600000 * 5));
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            //dataType: "json",
            contentType: "application/json",
            data: JSON.stringify(frm.serializeObject()),
            success: function(data, textStatus, request) {
                if (request.status == 202) {
                    $cookies.put('diprLogin', 'admin', {
                        expires: now
                    });
                    $window.location.href = '#';  
                    **var roleValue=data[0].role;**
                    console.log(roleValue);
                    $scope.$apply(function() {
                        $scope.noty.add({
                            type: 'info',
                            title: 'Welcome. Admin'
                        });
                    });
                }
            },
            error: function(jqXHR, textStatus, errorMessage) {
                $scope.$apply(function() {
                    $scope.noty.add({
                        type: 'danger',
                        title: 'Authentication failed',
                        body: 'Please try again...'
                    });
                });
            }
        });
        ev.preventDefault();
    });    
}]) //End loginCtrl

I want to send roleValue to every controllers to check some validation. Please help me in figuring how to do this. Also, can i call ajax from another controllers to return this variable?


Solution

  • Try these steps it will work :

    Step 1 : Create a service.

    angular.module('app').service('dataStoreService', function() {
        var data = '';
        function setData(newData){
            data = newData;
        }
    
        function getData(){
            return data;
        }
    })
    

    Step 2 : In your ajax call you can set the roleValue into the service.

    dataStoreService.setData(roleValue);
    

    Step 3 : Inject the dataStoreService as a dependency in the controllers where you want to get the roleValue. and call getData function of the dataStoreService from controller.

    dataStoreService.getData();