gpt4 book ai didi

javascript - 如何使用函数将值更改为范围内的全局变量? ("controller as")

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:43:38 24 4
gpt4 key购买 nike

我需要通过名为 checkusername 的函数更改作用域中 this.usernamevalid 变量的值,该函数是从如下 View 触发的:

register.jade:(ng-controller="controller as txt")

input(type="text", ng-model="formData.username",ng-blur="txt.checkusername('username',formData.username);" )

函数checkusername是:

regController.js

 ngApp.controller('controller', Main );

function Main(){
//I need to set this variable to true;
this.usernamevalid = false;




//In the View, I trigger this function
this.checkusername = function(param, val) {

if (val != undefined) {
$http.get('http://localhost:3000/users?param='+param+'&val='+val)
.then(function(response){
var size = response.data.length;
switch (param) {
case 'username':
if (size>0) {
//The user exist (DOES NOT WORK)
this.usernamevalid = true;
} else {
//The user don't exist (DOES NOT WORK)
this.usernamevalid = false;
}
break;
default:
console.log('Field undefined, STOP');
}
}, function(response){
alert(response + "(error)");
});
}


}

}

我尝试使用回调函数,但结果是一样的,我无法修改 this.usernamevalid 的结果,因为“this is not defined”。

最佳答案

基本上 $http.get 函数 .then 中的 this 与你的 this 是不一样的 Controller 上下文。

所以你应该像下面这样在你的 Controller 函数中创建一个变量。

var vm = this;

这将使您的 this 上下文在使用 vm 变量的 Controller 中随处可用。只需将 this 替换为 vm ,无论您在哪里使用 this

代码

ngApp.controller('controller', Main);
function Main() {
var vm = this; //created local variable which will have this reference.
//I need to set this variable to true;
vm.usernamevalid = false;
//In the View, I trigger this function
vm.checkusername = function(param, val) {
if (val != undefined) {
$http.get('http://localhost:3000/users?param=' + param + '&val=' + val)
.then(function(response) {
var size = response.data.length;
switch (param) {
case 'username':
if (size > 0) {
//The user exist (DOES NOT WORK)
vm.usernamevalid = true;
} else {
//The user don't exist (DOES NOT WORK)
vm.usernamevalid = false;
}
break;
default:
console.log('Field undefined, STOP');
}
}, function(response) {
alert(response + "(error)");
});
}
}
}

我强烈建议您继续阅读 this article

关于javascript - 如何使用函数将值更改为范围内的全局变量? ("controller as"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34474775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com