I have a directive that convert to 2 decimal places (input number textbox) and it is working well but I would like to pad the whole number with zeros.
Anyone knows how I can achieve whole number with padded zeros? Example below.
2 -> 2.00 - not done
10.666 -> 10.67 - done
app.directive('toPrecision',['$filter', function ($filter) {
return {
replace: false,
restrict: 'A',
link: function(scope, element, attr) {
var input = angular.element(element);
var precisionValue = attr.toPrecision;
input.on('keyup', function() {
var parsed = parseFloat(input.val());
if (!isNaN(parsed)) {
if (parseInt(parsed, 10) !== parsed && String(parsed).split('.')[1].length > 2) {
var result = parsed.toFixed(precisionValue);
input.val(result);
}
}
});
}
}
}]);
HTML
<input type="number" class="form-control" ng-model="rate" to-precision="2" min="0" step="1">
Ended rewriting the directives for what I want.
app.directive('toPrecision', function() {
return {
replace: false,
restrict: 'EA',
require: 'ngModel',
link: function(scope, element, attr, ngModelCtrl) {
var input = angular.element(element);
var precisionValue = attr.toPrecision;
ngModelCtrl.$parsers.push(function(value) {
var clean = value.replace(/[^-0-9\.]/g, '');
if (value !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
ngModelCtrl.$formatters.push(function(value) {
if (angular.isUndefined(value)) {
return "";
}
var parsed = parseFloat(value);
return parsed.toFixed(precisionValue);
});
input.on('blur', function() {
var parsed = parseFloat(input.val());
if (!isNaN(parsed)) {
var result = parsed.toFixed(precisionValue);
input.val(result);
ngModelCtrl.$setViewValue(result);
}
});
}
}});