如何从嵌套函数中设置父函数的变量值?

时间:2014-10-15 08:56:21

标签: javascript angularjs x-editable

我仍然是angularjs的初学者。对你来说这可能是个愚蠢的问题。我正在使用x-editable angularjs,我的问题是我无法在嵌套函数中设置值,我的代码如下所示。

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

     $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');
         }
      };
    

    `

2 个答案:

答案 0 :(得分:0)

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

  
      
  1. IAPIUserDetailService.checkUserName()是一个服务调用,它返回一个异步的promise对象,这样就可以执行下一行而无需等待服务调用的响应。因此,仅在获得响应后检查值。

  2.   
  3. this and _this are not two way bounded还有一件事要检查_this而不是this的值。

  4.   

答案 1 :(得分:0)

在这个例子中你不需要使用它,并且由于API调用的asyn特性,Raman指出你只能在响应到达后检查变量。所以你需要重写你的代码:

$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');
                    }
                });

  };