简体   繁体   中英

AngularJS ngKeyUp function the value is undefined

html

<input class="input--style" type="email" name="email" ng-model="attempt.email" ng-keyup="check(attempt.email)" value="">

angularjs

$scope.check = function(text){
                            console.log(text);
                            $http({
                                method: 'POST',
                                url: '/api/user/check/',
                                data: {'email': $scope.attempt.email},
                                headers: {'Content-Type': 'application/x-www-form-urlencoded'},                 
                            }).success(function(data, status, headers, config) {
                                console.log(data);
                                $scope.user.emailvalid = data.email;
                            });
                        }

This input is inside a modal and when the modal fires the angular above is inside that modals controller, it works as expected but when I start typing in the input field the console.log(text); outputs undefined

$scope.attempt = {} this is before my angular script above and I'm just curious as to why this isn't working.

Do you really want to make a call to the server every time that the user presses a key? Wouldn't you prefer to have a debounce of at least ~200ms?

Try doing this instead:

<input class="input--style" type="email" name="email" 
     ng-model="attempt.email" ng-model-options="{ debounce: 200 }" 
     ng-change="check(attempt.email)" >

Update:

I forgot to answer your original question: you are using an input type="email" , so unless it's a valid email angular will set the model to undefined . Therefore, angular is actually doing you a favor, because you probably don't want to make that call to the server unless the model contains a valid email address, right? So, just change your 'check' function so that it first checks if the value is undefined , and if it is don't make the call to the server and set $scope.user.emailvalid to false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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