AngularJS $http return value

ajax, angularjs, javascript

Solution

The problem is indeed with the async nature of call and when you are trying to access the variable. `console.log` returns null because it gets called before the `$http` call is complete.

Firstly we do not pollute the JavaScript global scope, but use services\factory, $rootScope to access data.

In you case if you want to expose a variable to across angular, the easiest way is to use $rootScope. Something like this

AdminController.controller('LoginController', ['$scope','$http','$location','$rootScope'
  function ($scope, $http, $location,$rootScope){
  $http({
        method: "post",
        url: "API/MyPage.php",
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function(data){
        $rootScope.sessionValues = eval(data);
        console.log($rootScope.sessionValues); /*Returns desired string*/
    }).error(function(){
        $scope.message="Some error has occured";
    });
    console.log($rootScope.sessionValues); /*Returns will always null due to async nature call*/
  }
]);

You then have to access that variable only after it has been filled in the success call back, before that it would be always null. The `console.log` would always fail.

To know when the variable value has changed you can use AngularJS watch http://www.benlesh.com/2013/08/angularjs-watch-digest-and-apply-oh-my.html

Problem

I am new to `AngularJS` and only aware of the basics of AngularJS. I want to return a value from `$http`. That is `$http` should return a value to the global variable of My Application. I have tried this: ``` var sessionValues = null; var AdminController = angular.module('AdminController', []); AdminController.controller('LoginController', ['$scope', '$http','$location', function ($scope, $http, $location){ $http({ method: "post", url: "API/MyPage.php", headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).success(function(data){ sessionValues = eval(data); console.log(sessionValues); /*Returns desired string*/ }).error(function(){ $scope.message="Some error has occured"; }); console.log(sessionValues); /*Returns null */ } ]); ``` I tried using `$rootScope`, but was not successful. I understand that this is because it is an asynchronous call, but how can I fetch the value in JS's global variable.? Can anyone help me about this.?

Original source