Skip to content

Instantly share code, notes, and snippets.

@ScottGuymer
Created April 1, 2014 09:04
Show Gist options
  • Save ScottGuymer/9910569 to your computer and use it in GitHub Desktop.
Save ScottGuymer/9910569 to your computer and use it in GitHub Desktop.
angular directive to format a number in an input
var common = angular.module('common', []);
/** allows numbers to be displayed from a model value with the correct decimal rounding */
common.directive('inputCurrency', function ($filter, $locale) {
return {
terminal: true,
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, ngModel) {
if (!ngModel)
return; // do nothing if no ng-model
// get the number format
var formats = $locale.NUMBER_FORMATS;
// construct the currency prefix
var outer = angular.element('<div />').addClass('input-group');
var span = angular.element('<span />').addClass('input-group-addon').html(formats.CURRENCY_SYM).appendTo(outer);
// insert it on the page and add the input to it
outer.insertBefore(element);
element.appendTo(outer).addClass('numeric');
// fix up the incoming number to make sure it will parse into a number correctly
var fixNumber = function (number) {
if (number) {
if (typeof number !== 'number') {
number = number.replace(',', '');
number = parseFloat(number);
}
}
return number;
}
// function to do the rounding
var roundMe = function (number) {
number = fixNumber(number);
if (number) {
return $filter('number')(number, 2);
}
}
// Listen for change events to enable binding
element.bind('blur', function () {
element.val(roundMe(ngModel.$modelValue));
});
// push a formatter so the model knows how to render
ngModel.$formatters.push(function (value) {
if (value) {
return roundMe(value);
}
});
// push a parser to remove any special rendering and make sure the inputted number is rounded
ngModel.$parsers.push(function (value) {
if (value) {
return fixNumber(roundMe(value));
}
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment