Reputation: 425
I'm new to JavaScript and Angular JS. I have to write a custom directive to validate the content of an input field passed in an .aspx page; more precisely I have to check if an username with the value passed in the input already exists. In my directve I have to call a service that checks for duplicates in the db and afterwards depending on the result I have to perform a success callback/error callback and to return an object containing info about the validation check and a message to diplay. In particular I'm stuck on this last part regarding callbacks and returning an object with info (in my version I cannot use $.defer).
Unfortunaltely, I cannot take advantage of the already existing custom validation for forms provided by Angular (that is $asynchrounous validators and $q.defer) as I have to use an older version of Angular 1.2.26. Could you provide me some hints/examples on how to achieve it? I'm trying hard but I still find custom directives a bit difficult and I cannot find examples for custom validation (except for those based on Angular 1.3 $asynch validators).
Thank you in advance
Upvotes: 0
Views: 194
Reputation: 17354
You can write your own directive for this: example
app.directive('asyncNameCheck', function($http){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attr, ngModel){
elm.bind('input', function(){
ngModel.$setValidity('asyncValid', false);
$http.get('http://graph.facebook.com/facebook')
.success(function(data){
ngModel.$setValidity('asyncValid', true);
});
})
}
}
})
and in the html
<form name="myform">
<input name="testfield" async-name-check required ng-model="test"/>
<p ng-show="myform.testfield.$error.asyncValid">This field is invalid</p>
</form>
Just note that this directive is not a reusable one but works for your requirements. Do not do this in the controller, I've spent a lot of time with angular validation and if you're controlling validation in the controller, it will cause you alot of issues later on.
Upvotes: 0
Reputation: 683
You can easily use $http service in your directive's link or controller function and do operations with response data. What is the problem exactly can you be more clear?
Upvotes: 1