Skip to content

Instantly share code, notes, and snippets.

@raecoo
Last active December 20, 2015 04:08
Show Gist options
  • Save raecoo/6068311 to your computer and use it in GitHub Desktop.
Save raecoo/6068311 to your computer and use it in GitHub Desktop.
Email Available directive for AngularJS
angular.directive "emailAvailable", ($http, $timeout) ->
require: 'ngModel'
link: (scope, elem, attrs, ctrl) ->
console.log ctrl
# push the validator on so it runs last.
ctrl.$parsers.push (viewValue) ->
# set it to true here, otherwise it will not
# clear out when previous validators fail.
ctrl.$setValidity "emailAvailable", true
if ctrl.$valid
# set it to false here, because if we need to check
# the validity of the email, it's invalid until the
# AJAX responds.
ctrl.$setValidity "checkingEmail", false
# now do your thing, chicken wing.
if viewValue isnt "" and typeof viewValue isnt "undefined"
$http.get("/email/" + viewValue + "/available").success((data, status, headers, config) ->
ctrl.$setValidity "emailAvailable", true
ctrl.$setValidity "checkingEmail", true
).error (data, status, headers, config) ->
ctrl.$setValidity "emailAvailable", false
ctrl.$setValidity "checkingEmail", true
else
ctrl.$setValidity "emailAvailable", false
ctrl.$setValidity "checkingEmail", true
viewValue
<div class="help-block" ng-show="signup.email.$dirty && signup.email.$invalid">Invalid:
<span ng-show="signup.email.$error.email">This is not a valid email.</span>
<span ng-show="signup.email.$error.checkingEmail">Checking email...</span>
<span ng-show="signup.email.$error.emailAvailable">Email not available</span>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment