Skip to content

Instantly share code, notes, and snippets.

@lukeandersen
Created August 8, 2016 04:33
Show Gist options
  • Select an option

  • Save lukeandersen/627c47c7033a0e8543299c8f84b6f6fb to your computer and use it in GitHub Desktop.

Select an option

Save lukeandersen/627c47c7033a0e8543299c8f84b6f6fb to your computer and use it in GitHub Desktop.
Numbers only in text input - Angular directive
'use strict';
angular.module('myApp').directive('numbersOnly', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
options: '=numbersOnly'
},
link: function (scope, element, attrs, ngModel) {
/* istanbul ignore if */
if (!ngModel) {
return;
}
var min = (scope.options && scope.options.min) ? scope.options.min : null;
var max = (scope.options && scope.options.max) ? scope.options.max : null;
ngModel.$formatters.push(parseValue);
ngModel.$parsers.push(parseValue);
function parseValue(inputValue)
{
ngModel.$setValidity('invalidMinimum', true);
ngModel.$setValidity('invalidMaximum', true);
if (inputValue) {
// if initial loading of the model, and there was no value previously set, remove invalid
var resetInvalid = (isNaN(ngModel.$viewValue));
// strip out anything thats not a number
inputValue = inputValue.replace(/[^0-9]/, '');
// check for minimum
if (min != null && parseInt(inputValue) < min) {
ngModel.$setValidity('invalidMinimum', false);
/* istanbul ignore if */
if (resetInvalid) inputValue = '';
}
// check for maximum
if (max != null && parseInt(inputValue) > max) {
ngModel.$setValidity('invalidMaximum', false);
/* istanbul ignore if */
if (resetInvalid) inputValue = '';
}
ngModel.$setViewValue(inputValue);
ngModel.$render();
ngModel.$validate();
}
return inputValue;
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment