Skip to content

Instantly share code, notes, and snippets.

@auser
Created September 2, 2013 21:34
Show Gist options
  • Save auser/6417470 to your computer and use it in GitHub Desktop.
Save auser/6417470 to your computer and use it in GitHub Desktop.
var app = angular.module('validationExample', []);
app.controller('signupController', ['$scope', function($scope) {
$scope.submitted = false;
$scope.signupForm = function() {
if ($scope.signup_form.$valid) {
} else {
$scope.signup_form.submitted = true;
}
}
}]);
app.directive('ensureUnique', ['$http', '$timeout', function($http, $timeout) {
var checking = null;
return {
require: 'ngModel',
link: function(scope, ele, attrs, c) {
scope.$watch(attrs.ngModel, function(newVal) {
if (!checking) {
checking = $timeout(function() {
$http({
method: 'POST',
url: '/api/check/' + attrs.ensureUnique,
data: {'field': attrs.ensureUnique}
}).success(function(data, status, headers, cfg) {
c.$setValidity('unique', data.isUnique);
checking = null;
}).error(function(data, status, headers, cfg) {
checking = null;
});
}, 500);
}
});
}
}
}]);
@theRemix
Copy link

theRemix commented Dec 2, 2014

if you swap out line 20:

if (!checking) {

with a check for field is $dirty

if (!checking && c.$dirty ) {

then you won't get an 'invalid' when the form loads, and is pristine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment