how to send value of variable from ajax to another controllers

254 views Asked by At

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?

3

There are 3 answers

0
Rohìt Jíndal On BEST ANSWER

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();
0
Ramesh Rajendran On

Option 1

$localStorage

You can set the role value in local storage in your current controller and get the local storage value from another controller for check the condition

controller 1

$localStorage.set("role",role);

controller 2

if($localStorage.get(role)!=1)
{
return false;
}
..
.
.
// next code

Option 2

$sccokieStore

It will be works like Same as $localstorage,

Option 3

$service

You can assign the role value on service scope object. whenever you need to check that. you call that service and do it the authentication

Option 3

$Broadcast

it's one of the best option to do the authentication . It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.

You can do authentication in globally like app.run side check the current rout and validate the authentication then redirect the route/ not.

More details : Why do we use $rootScope.$broadcast in AngularJS?

0
Abdullah Al Noman On

There are many ways . Yes of course you can store values to cookies or local-storage. This two would be best option if you need to reuse the values in multiple controller . But if you will use the values once the best option would be to use $stateParams or $state if your are using ui router see the difference between the two . Another option would be to use $rootScope.