Skip to content Skip to sidebar Skip to footer

How To Change The Value To A Global Variable In The Scope Using A Function? ("controller As")

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: (

Solution 1:

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;

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);
   functionMain() {
     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)");
         });
       }
   }
 }

I'd highly recommend you to read up on this article

Post a Comment for "How To Change The Value To A Global Variable In The Scope Using A Function? ("controller As")"