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

时间:2015-12-26 20:02:20

标签: javascript angularjs

我需要通过名为 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 的结果,因为“这未定义”。

1 个答案:

答案 0 :(得分:4)

this函数$http.get内的.then基本上与控制器上下文的this不同。

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

var vm = this;

这将使您使用this变量在控制器中随处可用vm上下文。 只需将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