没办法访问angularjshttp响应回调函数:外的$ scope对象
问题说明
我有这个控制器用于保存个人的一些细节。我有一个单独的存储库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.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfkegf
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20