如何设置父函数's嵌套函数中的变量值
how to set parent function's variable value from nested function?
我还是angularjs的初学者。也许这对你来说是个愚蠢的问题。我使用的是x-editable angularjs,我的问题是我无法在嵌套函数中设置值,我的代码如下。
- this.error的起始值为false
- 在嵌套的then函数中,如果我发现错误,应该将其更新为true
- 但在函数之外,当我检查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');
}
});
};
根据上面的代码,存在一些错误。
checkUserName()是一个服务调用,它返回一个异步的promise对象,以便在不等待服务调用响应的情况下执行下一行。因此,只在得到响应后检查该值。
还有一件事是
this and _this are not two way bounded
,所以检查_this
的值而不是this
。
相关文章:
- 用嵌套函数和默认函数定义函数
- d3中堆栈函数和嵌套函数之间的差异
- JavaScript 中的嵌套函数和 “this” 关键字
- 嵌套到另一个函数中的Fancybox函数;不起作用
- Javascript中带有返回值的嵌套函数
- 访问嵌套函数结构中的JavaScript父函数变量
- 从嵌套函数访问函数属性
- 如何在javascript中使用嵌套函数作为生成器(使用“inner”yields)
- Javascript嵌套函数属性继承
- 具有嵌套对象数组的 Javascript 对象的递归搜索函数
- Facebook Javascript 函数嵌套循环
- 将动态 AJAX 函数嵌套在 JavaScript 函数中 - 并保持更新
- 对由多个groupBy函数嵌套的对象数组进行分组
- 从父函数返回什么以获取从子函数/嵌套函数返回的值
- jQuery匿名函数-嵌套函数
- ajax调用函数嵌套
- 函数嵌套括号的Python风格指南是什么?
- setTimeout函数中的关键字,该函数嵌套在on()方法下.但这并没有奏效
- 嵌套异步函数嵌套同步函数
- 如何克服函数嵌套