You can accomplish this using ng-model
along with $formatters
and $parsers
.
See more explanation here:
ngModel Formatters and Parsers
This is a TypeScript adaptation from some code I use to force currency formats.
app.directive('myModelFormat', ['$filter', function myModelFormatDirective($filter:ng.IFilterService):ng.IDirective {
return {
require: '?ngModel',
link: myModelFormatLink
};
function myModelFormatLink(scope:ng.IScope, elem:ng.IAugmentedJQuery, attrs:ng.IAttributes, ctrl:ng.INgModelController) {
if (!ctrl) {
return;
}
const decimalWithOneDigit:RegExp = new RegExp('\\' + STRINGS.decimalSym + '\\d$');
ctrl.$formatters.unshift(function myModelFormatFormatter(ignore:any):string {
return $filter(attrs['myModelFormat'])(ctrl.$modelValue)
});
ctrl.$parsers.unshift(function myModelFormatParser(viewValue:string):any {
const plainNumber:number = parseFloat(viewValue);
let formatted:string = $filter(attrs['myModelFormat'])(plainNumber);
// special case where they typed the decimal symbol but not a decimal value,
// make sure we don't remove the symbol which prevents them from typing a decimal
if (_s.endsWith(viewValue, STRINGS.decimalSym)) {
formatted += STRINGS.decimalSym;
}
// alternate special case, they typed one decimal number, don't force it to zero, at least not yet..
if (decimalWithOneDigit.test(viewValue)) {
formatted = formatted.substr(0, formatted.length - 1);
}
elem.val(formatted);
return plainNumber;
});
}
}]);