我仍然是angularjs的初学者。对你来说这可能是个愚蠢的问题。我正在使用x-editable angularjs,我的问题是我无法在嵌套函数中设置值,我的代码如下所示。
`
$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');
}
};
`
答案 0 :(得分:0)
根据上面的代码,有一些错误。
IAPIUserDetailService.checkUserName()是一个服务调用,它返回一个异步的promise对象,这样就可以执行下一行而无需等待服务调用的响应。因此,仅在获得响应后检查值。
- 醇>
this and _this are not two way bounded
还有一件事要检查_this
而不是this
的值。
答案 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');
}
});
};