无法访问angularjs中http响应回调函数之外的$ scope对象 [英] not able to access $scope object outside a http response callback function in angularjs
问题描述
我有这个控制器用于保存个人的一些细节。我有一个单独的存储库EntityRepository,其中定义了一个从数据库中获取用户性别的函数。
I have this controller for saving some details for an individual. I have a separate repository EntityRepository where a function to get the user gender from database is defined.
函数响应正常工作,当我在控制台上打印性别时它起作用的函数响应(console.log(inside:,$ scope.userGender);)。
The function response is working correctly and when I am printing the gender on console inside the function response it works(console.log("inside : ", $scope.userGender);).
但是在函数外部,值不是未定义的我得到了(console.log(outside:,$ scope.userGender);)
But outside the function the value is not undefined I am getting(console.log("outside : ", $scope.userGender);)
.controller('individualDetailsCtrl', function($scope, $rootScope, $location, EntityRepository) {
$scope.userGender = "";
$scope.entity = {
name: "",
gender: $scope.userGender,
dob: "",
pan: ""
};
EntityRepository.getUserGender()
.then(function(response){
$scope.userGender = response.data.gender;
console.log("inside : ", $scope.userGender);
})
.catch(function(errorResponse) {
$scope.error = errorResponse.data
});
console.log("outside : ", $scope.userGender);
});
我想从$ scope.entity.gender中的响应中保存性别,但我不是能够在函数范围之外访问$ scope.userGender的值。
I want to save the gender from the response in the $scope.entity.gender but I am not able to access the value of $scope.userGender outside the function scope.
由于$ scope是在控制器范围内定义的,我认为它应该能够访问它的值在函数响应之外。
Since $scope is defined in the scope of controller I think it should be able to access its values outside the function response.
推荐答案
您无法访问 $ scope的值的原因。在AJAX成功回调之外的userGender
很简单:AJAX是异步的,这意味着只有在此AJAX调用成功后才会分配此变量的值。在此AJAX调用成功之前,您应该调整代码,使其不依赖于 $ scope.userGender
的值。如果此值是绑定到标记中某个控件的数据,那么这不是问题,当从服务器检索值时,该值将稍微延迟。
The reason why you can't access the value of $scope.userGender
outside the AJAX success callback is simple: AJAX is asynchronous, meaning that a value to this variable will be assigned only after this AJAX call succeeds. You should adapt your code so that it doesn't depend on the value of $scope.userGender
before this AJAX call has succeeded. If this value is data bound to some control in the markup, then this is not a problem, the value will appear with a little delay when the value is retrieved from the server.
这篇关于无法访问angularjs中http响应回调函数之外的$ scope对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!