Use the following currency directive to apply decimal places.
app.directive('currency', function ($filter, $locale) {
return {
require: 'ngModel',
scope: {
min: '=min',
max: '=max',
ngRequired: '=ngRequired'
},
link: function (scope, element, attrs, ngModel) {
function clearValue(value) {
value = String(value);
var dSeparator = $locale.NUMBER_FORMATS.DECIMAL_SEP;
var clear = value.match(/[\+\-0-9\.]/g);
clear = clear ? clear.join("") : 0;
return clear;
}
ngModel.$parsers.push(function (viewValue) {
cVal = clearValue(viewValue);
return parseFloat(cVal);
});
element.on("blur", function () {
if (isNaN(ngModel.$modelValue)) {
ngModel.$modelValue = 0;
element.val($filter('currency')(clearValue(ngModel.$modelValue)));
}
else {
element.val($filter('currency')(ngModel.$modelValue));
}
});
ngModel.$formatters.unshift(function (value) {
return $filter('currency')(value);
});
scope.$watch(function () {
return ngModel.$modelValue
}, function (newValue, oldValue) {
runValidations(newValue)
})
function runValidations(cVal) {
if (!scope.ngRequired && isNaN(cVal)) {
return
}
if (scope.min) {
var min = parseFloat(scope.min)
ngModel.$setValidity('min', cVal >= min)
}
if (scope.max) {
var max = parseFloat(scope.max)
ngModel.$setValidity('max', cVal <= max)
}
}
}
}
});
source
share