Created
September 2, 2013 21:34
-
-
Save auser/6417470 to your computer and use it in GitHub Desktop.
Validation example for http://www.ng-newsletter.com/posts/validations.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}); | |
} | |
} | |
}]); |
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
Try to use attrs.ngModel instead of attrs.ensureUnique