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); | |
} | |
}); | |
} | |
} | |
}]); |
Try to use attrs.ngModel instead of attrs.ensureUnique
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
I have tried this example, but it just keeps forwarding the data
{field: username} to the url of /api/check/username
I want to send the actual data typed inside the textbox.
This is my codes. It did not work. Please advise.
https://github.com/simkimsia/ng-book/tree/e4ee74b9cb64c9462be9587bda73a4ee53de708b/examples/http-api-server
Please look at index.html and js/api.js for the details.
This is solved by the comment at http://www.ng-newsletter.com/posts/validations.html#comment-1098281170
--- the SOLVED version of my codes ---
https://github.com/simkimsia/ng-book/tree/d2b6d7d261908a4242f3c36280babc15d9b46eb9/examples/http-api-server