I need a directive that performs an API request as a $parsers function.
<input type="text" name="referer" id="referer" ng-model="Subscribe.user.referer" check-referer>
My directive looks like
app.directive('checkReferer', [ 'subscriptionService', function( subscriptionService ) {
return {
restrict: 'A',
require: 'ngModel',
link: function( scope, element, attrs, ngModel ) {
ngModel.$parsers.unshift( function( viewValue ) {
subscriptionService.checkReferer( viewValue )
.then(function( response ) {
if ( typeof response.data == 'object') {
ngModel.$setValidity('validReferer', true );
return viewValue;
}
});
});
}])
I shortened the code a little bit for readability. The service is super straightforward (inside a service):
subscriptionService.checkReferer: function( email ) {
var promise = $http.get( settings.ApiUrl + 'check-referer/' + email )
.then( function( response ) {
return response;
}, function(response) {
// error handling here
})
return promise;
},
Problem is: when i 'return viewValue' after the promise has been loaded, the $modelValue doesn't change, so basically the promise doesn't alter the Subscribe.user.referer passed via ng-model to the directive. Everything is fine if i return anything different than a promise, so the problem is there, don't know how to solve it :(
I have no problems if i pass the value i want to change as an attribute to directive's scope. But that's not how i wanna do that :)
I'm not super familiar with Angular but I've been using it for a while now. It took me the whole morning to try to find an answer myself. No luck. And a bit frustrated.
Any help is GREATLY appreciated.