Created
June 4, 2014 03:58
-
-
Save enab-dev/5234564aba086b1932ef to your computer and use it in GitHub Desktop.
AngularJS Directive To Allow Only Numbers and CTRL+C or CTRL+V
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
.directive('numbersOnly', function () { | |
return { | |
restrict: 'A', | |
link: function (scope, elm, attrs, ctrl) { | |
// record ctrl key being down for ctrl+v and ctrl+c | |
var ctrlDown = false; | |
// reset the ctrl key flag on keyup | |
elm.on('keyup', function (event) { | |
ctrlDown = false; | |
}); | |
elm.on('keydown', function (event) { | |
if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) { | |
// backspace, enter, escape, arrows | |
return true; | |
} else if (event.which >= 48 && event.which <= 57) { | |
// numbers | |
return true; | |
} else if (event.which >= 96 && event.which <= 105) { | |
// numpad number | |
return true; | |
} else if (event.which === 17) { | |
// ctrl key or command key on a Mac | |
ctrlDown = true; | |
} else if (ctrlDown && [86, 67].indexOf(event.which) > -1) { | |
// ctrl+c or ctrl+v | |
return true; | |
} else { | |
event.preventDefault(); | |
return false; | |
} | |
}); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice job man. Helped allot. Next step could be some unit tests 😄