从工厂返回数据后,我尝试用$ scope.dummyTask分配这些数据。分配后我可以在回调函数中的控制台中显示这些。但是在功能块外面,$ scope.dummyTask是未定义的,但为什么呢?
$scope.dummyTasks=[];
$scope.getTask=function(){
Task.query(function(data){
$scope.dummyTasks=data;
console.log(angular.toJson($scope.dummyTasks));//shows desired data
});
};
$scope.getTask();
console.log(angular.toJson($scope.dummyTasks));// shows undefined
答案 0 :(得分:0)
它显示未定义,因为Task.query()
进行异步查询。
它很可能发送一个http请求,只有当响应可用时,才会调用回调函数,并初始化$scope.dummyTasks
。
// T0. send a query
Task.query(function(data) {
// T2 (long after T1). initialize dummyTasks from the asynchronous response
$scope.dummyTasks = data;
console.log(angular.toJson($scope.dummyTasks));//shows desired data
});
// T1 (immediately after T0). display $scope.dummyTasks
console.log(angular.toJson($scope.dummyTasks));// shows undefined