如何设置父函数's嵌套函数中的变量值

how to set parent function's variable value from nested function?

本文关键字:函数 嵌套 变量值 设置 何设置      更新时间:2023-09-26

我还是angularjs的初学者。也许这对你来说是个愚蠢的问题。我使用的是x-editable angularjs,我的问题是我无法在嵌套函数中设置值,我的代码如下。

  1. this.error的起始值为false
  2. 在嵌套的then函数中,如果我发现错误,应该将其更新为true
  3. 但在函数之外,当我检查error的值时,它仍然是false

`

 $scope.checkUserName = function(userName) {  
  // default value is false.
  this.error = false;
  var _this = this;
  IAPIUserDetailService.checkUserName(userName,$scope.user.id)
            .then(
                function( userResponse) {
                    if (userResponse.code == 400) {
                         // i have to update value here
                        _this.error = 'user already exist';  
                    }
                });
     // if there is an error still the value of error variable is false.
     if(this.error !==  false){
        $scope.editableForm.$setError('username', 'username already exist');
     }
  };

`

您不需要在本例中使用它,正如Raman所指出的,由于API调用的asyn性质,您只能在响应到达后检查变量。所以你需要重写你的代码:

$scope.checkUserName = function(userName) {  
  // default value is false.
  IAPIUserDetailService.checkUserName(userName,$scope.user.id)
            .then(
                function( userResponse) {
                    if (userResponse.code == 400) {
                         // i have to update value here
                       // if there is an error still the value of error variable is false.
                       $scope.editableForm.$setError('username', 'username already exist');
                    }
                });
  };

根据上面的代码,存在一些错误。

  1. checkUserName()是一个服务调用,它返回一个异步的promise对象,以便在不等待服务调用响应的情况下执行下一行。因此,只在得到响应后检查该值。

  2. 还有一件事是this and _this are not two way bounded,所以检查_this的值而不是this