ng-model
と$formatters
と$parsers
を使用してこれを行うことができます。
はこちらより詳細な説明を参照してください:
ngModel Formatters and Parsers
これは私が通貨形式を強制するために使用するいくつかのコードから活字体の適応です。
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;
});
}
}]);
私の懸念は、私はngPatternはちょうどあなたのボックス内の現在のテキストが正規表現に合うかどうかのtruthy値を与える入力ボックス –
に貼り付けるいたときに数字がフォーマットされていないです。あなたはそれが好きなように扱うことができます。参照:https://docs.angularjs.org/api/ng/directive/ngPattern – Araymer