Reputation: 1710
So i'm new to the whole web thing and today i discover about $asyncValidators.
So after a lot of trying i get stuck with this example.
username.validator
(function() {
angular
.module('app')
.directive('emailNotUsed',emailNotUsed);
emailNotUsed.$inject = ['$http', '$q'];
function emailNotUsed ($http, $q) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.emailNotUsed = function(modelValue, viewValue) {
console.log("start");
console.log(viewValue);
console.log($http.post('/email', viewValue));
$http.post('/email',viewValue).then(function(response) {
console.log("Check if email is valid in directive")
console.log(response.data)
return response.data == true ? $q.reject(response.data.errorMessage) : true;
});
};
}
};
}
}());
register.html
<div class="container" ng-controller="RegisterController as vm">
<div class="col-md-6 col-md-offset-3">
<h2>Register</h2>
<div ng-show="vm.error" class="alert alert-danger">{{vm.error}}</div>
<form name="form" ng-submit="!form.$pending && form.$valid && vm.register()" role="form">
<div class="form-group" ng-class="{ 'has-error': form.email.$dirty && form.email.$error.required }">
<label for="email">Email</label>
<input type="text" name="email" id="email" class="form-control" ng-model="vm.user.email" email-not-used ng-model-options="{ debounce: 500 }" required />
<div ng-messages="form.email.$error">
<div ng-message="emailNotUsed">User with this email already exists.</div>
</div>
</div>
<div class="form-actions">
<button type="submit" ng-disabled="form.$invalid || vm.dataLoading" class="btn btn-primary">Register</button>
<a href="#/login" class="btn btn-link">Cancel</a>
</div>
</form>
</div>
</div>
And now the where it got weird this is the output in the console
So why does this gives an error while i got the promise value? Any idea how to proceed
Upvotes: 1
Views: 2069
Reputation: 34796
Asynchronous validators expect promise to be returned, you must therefore modify your validation function to return the result of $http
call like this:
ngModel.$asyncValidators.emailNotUsed = function(modelValue, viewValue) {
return $http.post('/email',viewValue).then(function(response) {
return response.data == true ? $q.reject(response.data.errorMessage) : true;
});
};
Upvotes: 2