Skip to content

Instantly share code, notes, and snippets.

@brandly
Created March 23, 2015 15:04
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 brandly/3da04426832fc827eff1 to your computer and use it in GitHub Desktop.
Save brandly/3da04426832fc827eff1 to your computer and use it in GitHub Desktop.
only numbers directive
'use strict';
angular.module('onlyNumbers')
.directive('onlyNumbers', function () {
var allowedValues = [
'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '.'
];
return {
restrict: 'A',
scope: {},
link: function (scope, element, attrs) {
function checkIfAllowed(event) {
var character = String.fromCharCode(event.which);
if (allowedValues.indexOf(character) !== -1) {
return true;
} else {
event.preventDefault();
}
}
element.on('keypress', checkIfAllowed);
scope.$on('$destroy', function () {
element.off('keypress', checkIfAllowed);
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment