如何在Angularjs中的$ http.get之外访问结果

时间:2015-01-29 14:31:38

标签: javascript ajax angularjs http

如何在成功回调函数之外访问$http.get的结果?

我的代码是

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

        });

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

我未定义。

2 个答案:

答案 0 :(得分:2)

您需要返回承诺并在回调中发出警报:

// 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);

});

答案 1 :(得分:0)

var promise = $http.get('http://server/');

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