Angular $resource,函数调用后丢失作用域变量
Angular $resource, lose scope variable after function call
var createAttendances = function(){
var stud = StudentResource.get(function(data){
$scope.students = data.students;
console.log($scope.students);
});
console.log(stud.students);
console.log($scope.sudents);
};
在资源获取函数中,它打印出两个对象的数组(很好)
外部资源得到它打印出来 undefined
它看到了 stud 对象,但是当我向学生查询参数时它 returns undefined
如您所见,主要问题是获取 $scope.students 或 data.students ouside StudentResouce.get func
StudentResource.get
是一个异步调用,这意味着它下面的行甚至可以在 Resource GET 调用完成之前执行,这就是您的变量在回调之外返回 undefined 的原因。
要访问您通过 GET 调用获取的数据,您必须在回调本身内部查询它。
这是一个异步调用,所以你可以通过这种方式得到结果,我一开始也有同样的困惑。
StudentResource.get().$promise.then(function (result) {
$scope.students = result.students;
console.log($scope.students);
})
var createAttendances = function(){
var stud = StudentResource.get(function(data){
$scope.students = data.students;
console.log($scope.students);
});
console.log(stud.students);
console.log($scope.sudents);
};
在资源获取函数中,它打印出两个对象的数组(很好) 外部资源得到它打印出来 undefined
它看到了 stud 对象,但是当我向学生查询参数时它 returns undefined
如您所见,主要问题是获取 $scope.students 或 data.students ouside StudentResouce.get func
StudentResource.get
是一个异步调用,这意味着它下面的行甚至可以在 Resource GET 调用完成之前执行,这就是您的变量在回调之外返回 undefined 的原因。
要访问您通过 GET 调用获取的数据,您必须在回调本身内部查询它。
这是一个异步调用,所以你可以通过这种方式得到结果,我一开始也有同样的困惑。
StudentResource.get().$promise.then(function (result) {
$scope.students = result.students;
console.log($scope.students);
})