Reputation: 87
Trying to add an asyncvalidator to my custom username validator. However it outputs the error:
TypeError: Cannot set property 'username' of undefined.
How to I make asyncvalidator defined? I thought i would have been automatically by the NgModel controller?
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
angular.module('myApp.commonDirectives', ['myApp.services']).directive('username', ['UsernameService',function(UsernameService){
return {
restrict: 'A',
require: "ngModel",
scope: {
hasFocus: "=username"
},
link: function(scope, element, attrs, ctrl) {
scope.$watch('hasFocus', function(hasFocus) {
if(angular.isDefined(hasFocus)) {
// on blur
if(!hasFocus) {
ctrl.$validated=false;
ctrl.$asyncValidators.username = function(value){
UsernameService.validate(value)
.then(function(resolvedData) {
if(resolvedData) {
ctrl.$validated=true;
ctrl.$setValidity('checking', true);
// ctrl.$setValidity('username', true);
}
else {
ctrl.$validated=true;
ctrl.$setValidity('checking', false);
// ctrl.$setValidity('username', false);
}
}
);
}
}
// on focus
else {
ctrl.$setValidity('username', true);
ctrl.$setValidity('checking', true);
}
}
});
}
}
}])
Upvotes: 0
Views: 1912
Reputation: 360
$asyncValidators
is available from angularjs 1.3 and above:
https://code.angularjs.org/1.2.27/docs/api/ng/type/ngModel.NgModelController
Upvotes: 2
Reputation: 453
try something like this :
angular.module('myModule').directive('usernameValidator', function($http, $q) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.username = function(modelValue, viewValue) {
return $http.post('/username-check', {username: viewValue}).then(
function(response) {
if (!response.data.validUsername) {
return $q.reject(response.data.errorMessage);
}
return true;
}
);
};
}
};
});
Upvotes: -1