5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ngModelのFormattersとParsersの使い方

Posted at

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);
            });
        }
    };
});

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?