Skip to content

Instantly share code, notes, and snippets.

@camshaft
Created October 26, 2012 19:58
Show Gist options
  • Select an option

  • Save camshaft/3961097 to your computer and use it in GitHub Desktop.

Select an option

Save camshaft/3961097 to your computer and use it in GitHub Desktop.
Angular.js Custom Validator
var deps = [
'myapp.services',
'myapp.directives',
'myapp.controllers'
];
var app = angular.module('myapp', deps);
var controllers = angular.module('myapp.controllers', []);
var MyAppController = [
"$scope",
"checkUserName",
function ($scope, checkUserName) {
$scope.checkUserName = checkUserName;
}
]
controllers.controller('MyAppController', MyAppController);
var directives = angular.module('myapp.directives', []);
directives.directive('duplicate', [
function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
var fun = function() {
scope[attrs.duplicate](elem.val(), function(valid) {
ctrl.$setValidity('duplicate', !!valid);
});
};
// Validate as the model changes
scope.$watch(attrs.ngModel, fun);
// Check the value on load
fun();
}
}
}
]);
var services = angular.module('myapp.services', []);
services.factory('checkUserName', [
'$http',
function($http) {
var reqs = {};
return function(contactName, done) {
// Make an $http call here to check with the server
done(null, false);
};
}
]);
<div data-ng-app="myapp" data-ng-controller="MyAppController">
<input data-ng-model="userName" type="text" data-duplicate="checkUserName">
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment