简体   繁体   English

输入框中的AngularJS货币格式

[英]Angularjs currency formatting in input box

Hi! 嗨! I have the following input box : 我有以下输入框:

<div ng-repeat="item in items"
    <input ng-model="item.cost" />
</div>

I am trying to figure out how to apply "currency" filter to the input box. 我试图弄清楚如何将“货币”过滤器应用于输入框。 So that when value is displayed it displays with $ sign and proper currency notations. 这样,当显示值时,将显示$符号和正确的货币符号。 I can do with span using {{item.cost | currency }} 我可以使用{{item.cost | currency }} {{item.cost | currency }} but I need the box to be editable to change the value if needed. {{item.cost | currency }}但我需要此框可编辑以在需要时更改值。 Please let me know how I can apply currency filter to the input box. 请让我知道如何将货币过滤器应用于输入框。 Thanks 谢谢

Try this 尝试这个

.directive('currencyFormatter', ['$filter', function ($filter) {


            formatter = function (num) {
              return $filter('currency')(num);
            };

        return {
          restrict: 'A',
          require: 'ngModel',
          link: function (scope, element, attr, ngModel) {
            ngModel.$parsers.push(function (str) {
             return str ? Number(str) : '';
            });
            ngModel.$formatters.push(formatter);

            element.bind('blur', function() {
              element.val(formatter(ngModel.$modelValue))
            });
            element.bind('focus', function () {
              element.val(ngModel.$modelValue);
            });
          }
        };
      }]);

And the html 和HTML

<div ng-repeat="item in items">
    <input ng-model="item.cost" currency-formatter/>
  </div>
 <div ng-repeat="item in items">
    {{item.cost}}
  </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM