• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

没办法访问angularjshttp响应回调函数:外的$ scope对象

用户头像
it1352
帮助1

问题说明

我有这个控制器用于保存个人的一些细节。我有一个单独的存储库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.

正确答案

#1

您无法访问 $ 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
系列文章
更多 icon
同类精品
更多 icon
继续加载