我需要改变的 this.usernamevalid 通过调用函数的变量范围内的 checkusername ,这个功能是从这样的观点引发的值:
I need to change the value of the this.usernamevalid variable in the scope via a function called checkusername, this function is triggered from the view like this:
register.jade:(NG-控制器=控制器为txt)
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 ,因为这不是定义。
基本上这个
中的 $ http.get
函数。然后
是不一样的这个
控制器上下文的。
Basically the this
inside the $http.get
function .then
is not the same this
of your controller context.
所以,你应该在你的控制器函数创建一个变量如下图所示。
So you should create a variable in your controller function like below.
var vm = this;
这将使你的使用控制器随处可见这种
背景 VM
变量。只需更换这个
与 VM
无论你使用这个
Which will make your this
context available everywhere in controller using vm
variable.
Just replace this
with vm
wherever you have used this
code
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)");
});
}
}
}
我强烈建议您在 本文