Created
October 26, 2012 19:58
-
-
Save camshaft/3961097 to your computer and use it in GitHub Desktop.
Angular.js Custom Validator
This file contains hidden or 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 deps = [ | |
| 'myapp.services', | |
| 'myapp.directives', | |
| 'myapp.controllers' | |
| ]; | |
| var app = angular.module('myapp', deps); |
This file contains hidden or 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 controllers = angular.module('myapp.controllers', []); | |
| var MyAppController = [ | |
| "$scope", | |
| "checkUserName", | |
| function ($scope, checkUserName) { | |
| $scope.checkUserName = checkUserName; | |
| } | |
| ] | |
| controllers.controller('MyAppController', MyAppController); |
This file contains hidden or 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 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(); | |
| } | |
| } | |
| } | |
| ]); |
This file contains hidden or 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 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); | |
| }; | |
| } | |
| ]); |
This file contains hidden or 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
| <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