I am using ngChange in AngularJS to trigger a custom function that will remove any letters the user adds to the input.
Here's my implementation of the $parser solution that @Mark Rajcok recommends as the best method. It's essentially @pkozlowski.opensource's excellent $parser for text answer but rewritten to only allow numerics. All credit goes to him, this is just to save you the 5 minutes of reading that answer and then rewriting your own:
app.directive('numericOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
And you'd use it like this:
Interestingly, spaces never reach the parser unless surrounded by an alphanumeric, so you'd have to .trim() as needed. Also, this parser does NOT work on . For some reason, non-numerics never make it to the parser where they'd be removed, but they do make it into the input control itself.