JSFiddle - React, Tailwind, and code Playground
by Krzysztof Safjanowski
HTML
<div ng-app="currencyApp">
<form action="">currency: {{ currency }}
<br />
<input type="text" name="currency" ng-model="currency" currency-formatter="" />
</form>
</div>
JavaScript
angular.module('currencyApp', [])
.filter('roundToThousands', function () {
return function (input) {
var value = parseInt(input);
if((parseFloat(input) === value && !isNaN(input))) {
if(value < 0) {
return 1000;
} else if(value === 0) {
return 0;
} else if(value < 1000) {
return 1000;
} else {
return Math.round( value / Math.pow(10,3) )*Math.pow(10,3);
}
} else {
return input;
}
};
})
.directive('currencyFormatter',
function ($filter) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
if (!ngModel) {
return;
}
ngModel.$parsers.unshift(function () {
var parsedValue = parseFloat(parseFloat(ngModel.$viewValue));
if (angular.isNumber(parsedValue) && !isNaN(parsedValue)) {
return $filter('currency')($filter('roundToThousands')(parsedValue));
}
});
element.bind('blur', function () {
scope.$apply(function () {
if (ngModel.$modelValue) {
element.val(ngModel.$modelValue);
}
});
});
}
};
});