0

I have js file lets say: login.js where I have defined root scope variable and assigned some value, something like this:

mainApp.controller('loginController',function($sessionStorage, $scope, $location, $window, $http, $rootScope) {

        $scope.login = function() {



            $http.get('http://localhost:8080/user/').then(function(response) {
                $scope.users = response.data;

                var len=$scope.users.length;
                var i=0;
                var flag="false";
            for(i=0;i<len;i++)
                {
            if (($scope.login.userName == $scope.users[i].username) && ($scope.login.password== $scope.users[i].password)) 
                {

                $rootScope.uName1 = $scope.users[i].username;
                $sessionStorage.id=$scope.users[i].id;
                $sessionStorage.uName=$scope.users[i].username;


                alert($scope.uName);
                alert($scope.login.userName);
                alert($rootScope.uName1);

                    //$cookieStore.put('id',$scope.users[i].id);
                //  alert("id="+$cookieStore.get('id'));
                    flag="true";
                    break;  
                }
                }

Here I am able to get value in "uName1". Now I have tried to access same variable in another js file: "document.js"

    app.controller("docCtrl",function($sessionStorage, $scope, $location, $window, $http, $rootScope){  
        $scope.id=$sessionStorage.id;

        alert($rootScope.uName1);

Here I am getting undefined in alert. I have also tried using sessionStorage but no help. Please let me know if i missed something. Thank you so much in advance.

Raj
  • 65
  • 1
  • 2
  • 10
  • Use $rootScope.$on and $rootScope.$emit to communicate between controllers; just added an object to $rootScope does not work as far as I know. – Ramsing Nadeem Aug 17 '17 at 10:17

1 Answers1

0

$rootScope.uName1 will be available after sucessfully get ajax result. If your docCtrl controller get called before ajax return result then you will get undefined

Zamrony P. Juhara
  • 5,222
  • 2
  • 24
  • 40