我有这个 Angular Controller :
app.controller('FeedCtrl', function ($scope, Profile) {
$scope.getID = function() {
Profile.getUID()
.then(function (data) {
if (data !== null) {
console.log(data.id); // returns correct id
$scope.data = data;
} else {
console.log("Could not retrieve id");
}
}, function (error) {
console.log(error);
});
console.log($scope.data); // logs: undefined
return $scope.data; // logs: undefined
};
var somedata = $scope.getID();
console.log(somedata); //just returns undefined
});
Controller 用于 JSON 请求的工厂。
module.factory('Profile', function($http, $localStorage) {
return {
getUID:function(){
return $http.get("https://graph.facebook.com/v2.2/me", {params: { access_token: $localStorage.accessToken, fields: "id,name,gender,location,website,picture,relationship_status", format: "json" }})
.then(function(response) {
if (typeof response.data === 'object') {
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
}, function(response) {
// something went wrong
return $q.reject(response.data);
});
}
};
});
<小时/>
问题
我无法更改 $scope.data 的值以在 $scope.getID 函数之外但在 FeedCtrl 的其余部分内使用。
如果您查看评论,您会看到我在控制台日志中返回的内容。
我试图通过在 StackOverflow 和 Google 中搜索来理解这个问题,但似乎我不理解 AngularJS 的 $scope 概念。
我很感激任何朝着正确方向的插入。
最佳答案
这是一个典型的错误,您调用的代码是异步的,查看您的控制台并观察日志的顺序,将返回正确 id 的日志将是最后一个,因为它只会在 promise 已解决。
这对您来说足以插入您走向正确的方向吗?
非常简单example ,但原理是一样的。
setTimeout(function(){
document.write('A2: Timeout is done');
}, 5000);
document.write('A1: Called timeout, this gets logged before A2 even though my line number is higher.');
关于javascript - AngularJS 变量的变量范围/嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29333664/