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);
}
}
});
}
}
}])