0

How can I access the result of the $http.get outside of its success callback function?

My code is

$http.get('http://myserver/' + $scope.myE)
        .success(function(data) 
        {
            $scope.mydata = data;

        });

alert(JSON.stringify($scope.mydata));

I got undefined.

user3569641
  • 892
  • 1
  • 17
  • 50

2 Answers2

2

you need to return the promise and do your alert in the callback:

// define the function that does the ajax call
getmydata = function() {
    return $http.get('http://myserver/' + $scope.myE)
        .success(function(data) 
        {
            $scope.mydata = data;

        });

}


// do the ajax call
getmydata().then(function(data) {
    // stuff is now in our scope, I can alert it
    alert($scope.mydata);

});
ProblemsOfSumit
  • 19,543
  • 9
  • 50
  • 61
0
var promise = $http.get('http://server/');

promise.then(function(payload) {
    alert(payload);
});