Skip to content

Instantly share code, notes, and snippets.

@jacek-dargiel
Created September 9, 2014 12:39
Show Gist options
  • Select an option

  • Save jacek-dargiel/5f2b28e37772c01dbc74 to your computer and use it in GitHub Desktop.

Select an option

Save jacek-dargiel/5f2b28e37772c01dbc74 to your computer and use it in GitHub Desktop.
/**
* Remember to inject $q!
*/
ngModule.directive('usernameAvailableValidator', ['$http', '$q' function($http, $q) {
return {
require : 'ngModel',
link : function($scope, element, attrs, ngModel) {
ngModel.$asyncValidators.usernameAvailable = function(username) {
/**
* Create a new deffered object to use as the asyncValidator promise.
*/
var deferred = $q.defer();
/**
* Resolve the promise immediately, if the value is empty.
*/
if(angular.isUndefined(username) || username === ''){
deferred.resolve();
}
/**
* If it's not, run the $http request.
*/
else{
$http.get('/api/username-exists?u='+ username)
.success(function(){
deferred.resolve();
})
.error(function(){
deferred.reject();
});
}
return deferred.promise;
};
}
}
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment