I am currently doing a web application with AngularJS and a consumable API using SlimPHP.
When I register a user, I need to perform a check using a GET method. Depending on this method returns, I should run the $event.preventDefault()
or not.
The code of AngularJS is the following:
$scope.checkEmails = function(e){
var req = $http.get(url + 'adv/register/check?email=' + $scope.email).then(function(response){
if(response.data === true) {
e.preventDefault()
}
})
}
And the HTML button is this:
<button type="submit" class="btn btn-alt-success" ng-click="checkEmails($event)">
The problem is that, when i try to execute the e.preventDefault()
, inside scope of $http call the object $event is undefined.
So, how i can pass this object inside $http call , or how i can get the values from $http call outside of their scope to make the check outside the call.
Thanks!
Try like this
$scope.checkEmails = function(e){
var req = $http.get(url + 'adv/register/check?email=' + $scope.email).then(function(response){
if(response.data === true) {
$scope.submitForm =false;
} else{
$scope.submitForm = true;
}
})
Add ng-submit like this
<form ng-submit=“submitForm && submit()”>
Your setup will never work because the form is submitted long before the $http
request is resolved. A button with type="submit"
will submit its referring form immediately; due to JS asynchronous nature a delayed preventDefault()
has no effect. So avoid submitting the form through a submit button and do it by code instead. There is multiple ways, in plain JS :
document.getElementById('formId').submit()
ie:
<button type="button" class="btn btn-alt-success" ng-click="checkEmails()">
^^^^^^^^^^^^^
$scope.checkEmails = function(e) {
$http.get(url + 'adv/register/check?email=' + $scope.email).then(function(response){
if (response.data !== true) {
document.getElementById('formId').submit()
}
})
}
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.