Skip to content

Instantly share code, notes, and snippets.

@joseadrian
Forked from enab-dev/angular.numbers_only.js
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joseadrian/bbe96f3894b13acca87d to your computer and use it in GitHub Desktop.
Save joseadrian/bbe96f3894b13acca87d to your computer and use it in GitHub Desktop.
.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