繁体   English   中英

如何使用函数将值更改为范围中的全局变量? (“控制器为”)

[英]How to change the value to a global variable in the scope using a function? (“controller as”)

我需要通过名为checkusername的函数更改作用域中this.usernamevalid变量的值,此函数从视图中触发,如下所示:

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里面$http.get功能.then是不一样的this控制器上下文。

所以你应该在控制器函数中创建一个变量,如下所示。

var vm = this;

这将使您的this上下文在使用vm变量的控制器中随处可用。 只需更换thisvm无论你使用了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)");
         });
       }
   }
 }

我强烈建议你阅读这篇文章

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM