Posted at

ngModelのFormattersとParsersの使い方

More than 3 years have passed since last update.

inputの入力と出力に変換を挟ませるやり方



/**

* inputの値をcurrencyCodeを元にフォーマットする
*
* usage:
* <input type="text" amount-format="currencyCode">
*/

context.app.directive("amountFormat", function ($parse:ng.IParseService) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope:ng.IScope, element:ng.IAugmentedJQuery, attrs:ng.IAttributes, ngModel:ng.INgModelController) {
var currencyCode = $parse(attrs["amountFormat"])(scope);
var currencyInfo = Currency.getInformationByCode(currencyCode);
var offset = currencyInfo.map((x)=>x.offset).getOrElse(1);

// model から view へ
ngModel.$formatters.push(function toView(amount) {
if(_.isUndefined(amount)) {
return NaN;
}

return parseFloat((amount / offset).toFixed((offset == 100) ? 2 : 0));
});

// view から model へ
ngModel.$parsers.push(function(amount) {
return (amount * offset).toFixed(0);
});
}
};
});