Skip to content

Instantly share code, notes, and snippets.

@ronaldofs
Created July 14, 2016 08:55
Show Gist options
  • Save ronaldofs/62ffa46f1a29dc448f973be7864285d0 to your computer and use it in GitHub Desktop.
Save ronaldofs/62ffa46f1a29dc448f973be7864285d0 to your computer and use it in GitHub Desktop.
Angular 1.x directive for handling number input
angular
.module('angular-number-input', [])
.directive('number-input', NumberInput);
function NumberInput() {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
scope.$watch(attrs.ngModel, watchValue);
function watchValue(newValue, oldValue) {
if (newValue === "" || newValue === oldValue) return;
var strValue = new String(newValue);
var parts = splitNumber(strValue);
if (!parts) return updateViewValue(oldValue || '');
var value = [
allowNegative() && parts[1],
parts[2],
allowDecimal() && parts[3],
allowDecimal() && parts[4] && trimDecimals(parts[4], parseInt(attrs.decimalUpto, 10))
].filter(identity).join('');
return strValue !== value && updateViewValue(value);
}
function identity(o) { return o }
function splitNumber(num) { return num.match(/^(-?)([0-9]+)?([,|\.])?([0-9]+)?$/) }
function allowNegative() { return attrs.allowNegative !== 'false' }
function allowDecimal() { return attrs.allowDecimal !== 'false' }
function trimDecimals(str, max) { return str.slice(0, max || str.length) }
function updateViewValue(value) {
ngModel.$setViewValue(value);
ngModel.$render();
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment