Sabyasachi Sabyasachi - 3 months ago 50
AngularJS Question

asynchronous validator to return a promise but got 'undefined' instead - inside mddialog angular material

I am using Anggular Material mdDialog to show a small Form inside a Dialog Box.
I am calling a directive username-available to do asynchronous validation inside it.

dialog.tmpl.html:

<md-dialog aria-label="Save Scenario">
<form name="userForm" novalidate >

<input style="display:inline-block" name="Name" ng-model="SaveScenario.ScenarioName" ng-pattern="pattern"
required username-available ng-model-options="{ updateOn: 'blur' }">

</form>
</md-dialog>


app.js:

module.directive('usernameAvailable', function($timeout, $q,UserService) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attr, ngModel) {
ngModel.$asyncValidators.usernameExists = function(modelValue, viewValue) {


var currentValue = modelValue || viewValue;

UserService.checkifScenarioNameExists(currentValue)
.then(
function (d)
{
console.log("the data object from promise is", d.data);
if ( d.data == true)
{
console.log("username exists");
// deferred.resolve(d.data);
return $q.resolve(d.data);
}
else
{
console.log("username does not exist");
ngModel.$setValidity('usernameExists', false);

return $q.reject(d.data);
}


},
function (errResponse) {
console.error('The Promise was unsuccessfull');
}

);

};
}
}
});


Here is how my Dialog Box looks like and the error are also displayed:

Dialog Box

I think my syntax for returning a promise inside the directive is correct. I am not sure if it could be something with md-dialog.
Can someone please help out why this error is happening??

Answer

As error states, expected asynchronous validator to return a promise. Inside validator, you missed return statement in front of your UserService usage.

return UserService.checkifScenarioNameExists(currentValue).then(...)