【问题标题】:not able to access $scope object outside a http response callback function in angularjs无法在 angularjs 中的 http 响应回调函数之外访问 $scope 对象
【发布时间】:2016-04-05 07:26:14
【问题描述】:

我有这个控制器来保存个人的一些细节。我有一个单独的存储库 EntityRepository,其中定义了从数据库获取用户性别的函数。

函数响应工作正常,当我在函数响应内的控制台上打印性别时,它工作正常(console.log("inside : ", $scope.userGender);)。

但在函数之外,我得到的值不是未定义的(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 的值。

由于 $scope 是在控制器范围内定义的,我认为它应该能够在函数响应之外访问其值。

【问题讨论】:

    标签: javascript angularjs angularjs-scope


    【解决方案1】:

    无法在 AJAX 成功回调之外访问 $scope.userGender 的值的原因很简单:AJAX 是异步的,这意味着只有在此 AJAX 调用成功后才会为该变量赋值。您应该调整您的代码,使其在此 AJAX 调用成功之前不依赖于 $scope.userGender 的值。如果这个值是绑定到标记中某个控件的数据,那么这不是问题,当从服务器检索该值时,该值会稍微延迟出现。

    【讨论】:

    • 您要更正什么?你的代码没有问题。这就是 AJAX 的工作原理。在 AJAX 成功回调中使用 $scope.userGender 变量,而不是在它之外。调整您的代码,使其使用回调函数工作。
    【解决方案2】:

    由于请求的异步属性,您无法访问外部的值。这仅仅意味着这条语句:console.log("outside : ", $scope.userGender);,在.then(function(){ ... }) 之前执行。

    修复:

    1. 将外部代码包装在$timeout

    .controller('individualDetailsCtrl', function($scope, $rootScope, $location, EntityRepository, $timeout) {

    $timeout(function() {console.log("outside : ", $scope.userGender)});

    1. 仅在.then(function() { }) 内使用$scope.userGender 的值。

    【讨论】:

      【解决方案3】:

      你能试试这个吗?

        $scope.GetUserGender = function(){
       EntityRepository.getUserGender().then(function(response){
          $scope.userGender = response.data.gender;
          console.log("inside : ", $scope.userGender);
        }).catch(function(errorResponse) {
          $scope.error = errorResponse.data
        });     
      }
        $scope.GetUserGender();   //
      
       console.log("outside : ", $scope.userGender);
      

      希望这会奏效:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-23
        • 2017-01-26
        • 1970-01-01
        • 1970-01-01
        • 2018-05-09
        • 2023-03-06
        相关资源
        最近更新 更多