Skip to content

Instantly share code, notes, and snippets.

@KomanRudden
Created March 18, 2016 11:12
Show Gist options
  • Save KomanRudden/322f3ea4850f0927fb4d to your computer and use it in GitHub Desktop.
Save KomanRudden/322f3ea4850f0927fb4d to your computer and use it in GitHub Desktop.
AngularJS numeric directive
var app = angular.module('permgen.directives');
app.directive('numbersOnly', function () {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
if (text) {
var transformedInput = text.replace(/[^0-9]/g, '');
if (transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
return undefined;
}
ngModelCtrl.$parsers.push(fromUser);
}
};
});
<input type="text" numbers-only/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment