Skip to content

Instantly share code, notes, and snippets.

@enab-dev
Created June 4, 2014 03:58
Show Gist options
  • Save enab-dev/5234564aba086b1932ef to your computer and use it in GitHub Desktop.
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
.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;
}
});
}
}
});
@gavinprice
Copy link

Nice job man. Helped allot. Next step could be some unit tests 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment