Skip to content

Instantly share code, notes, and snippets.

@auser
Created September 2, 2013 21:34
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • 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);
}
});
}
}
}]);
@simkimsia
Copy link

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

@rcr866
Copy link

rcr866 commented Aug 21, 2014

Try to use attrs.ngModel instead of attrs.ensureUnique

@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