无法在 angularjs 中访问 http 响应回调函数之外的 $scope 对象 [英] not able to access $scope object outside a http response callback function in angularjs

查看:33
本文介绍了无法在 angularjs 中访问 http 响应回调函数之外的 $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.

推荐答案

在AJAX成功回调之外无法访问$scope.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆