当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Why isn't Angular's $scope accessible inside my call to Google App Engine data

问题描述:

I'm trying to create a controller that gets data from Google app engine and allows me to display it on a page. The problem seems to be that the data (resp) can be accessed locally, but I can't seem to access it outside of the function. I am able to do so if I simply use javascript (...document.getElementById('getListingsResult').innerHTML = result;...), but if I invoke $scope for Angular, I can't access it any longer. Does anyone have any idea of how I can fix it while retaining the same structure to load and call gapi? Heres' my code:

(edit: added $scope.loadData, but problem persists)

 phonecatControllers.controller('datastoreTestCtrl', ['$scope',

function($scope) {

$scope.data;

$scope.loadData = function() {

var ROOT = 'https://my_team.appspot.com/_ah/api';

gapi.client.load('listingserviceapi', 'v1', function(){

console.log("reached step 1");

var request = gapi.client.listingserviceapi.getListings();

request.execute(function (resp){

if (!resp.code) {

// console.debug(resp);

console.log('loaded! :)');//returns loaded

resp.items = resp.items || [];

$scope.data = resp.items;

console.log($scope.data); //returns an array of data

}

};

} , ROOT );};

$scope.loadData;

console.log($scope.data); //returns [object, object] which is incorrect

}]);

网友答案:

It should work using promise. Also, there is a missing parenthesis for request.execute function in your code.

Check the below code (untested):

phonecatControllers.controller('datastoreTestCtrl', ['$scope', '$q',

function ($scope, $q) {
    $scope.data = null;

    $scope.loadData = function () {
        var deferred = $q.defer(),
            ROOT = 'https://my_team.appspot.com/_ah/api';

        gapi.client.load('listingserviceapi', 'v1', function () {
            console.log("reached step 1");
            var request = gapi.client.listingserviceapi.getListings();
            request.execute(function (resp) {
                if (!resp.code) {
                    // console.debug(resp);
                    console.log('loaded! :)'); //returns loaded
                    resp.items = resp.items || [];
                    //$scope.data = resp.items;
                    //console.log($scope.data); //returns an array of data
                    deferred.resolve(resp.items);
                }
            }); //---missing parenthesis here
        }, ROOT);

        return deferred.promise;
    };

    $scope.loadData().then(function (data) {
        $scope.data = data;
        console.log($scope.data); //returns [object, object] which is incorrect
    });
}]);
网友答案:

That is because you are doing asynchronous call. When you trying to access $scope.data from outside of your callback your request is not finished yet it is still in process. You have to make sure that your request is done.

分享给朋友:
您可能感兴趣的文章:
随机阅读: