AngularJS - How do I apply a currency filter in a text box as I type?

In my project, there is a requirement to specify the amount field in the currency format. I can achieve this event onblur, but let me know if this can be done using filters or some other AngularJS methods.

I have the following text box:

<input type="text" class="form-control" id="MyAmount" name="MyAmount" ng-model="MyAmount" />

I want to convert the value inside this text box to follow the currency format. So, if I type 200,000, he should make $ 200,000.00 as soon as I type or while I type.

I used the following technique and applied a filter,

<input type="text" class="form-control" id="MyAmount" name="MyAmount" ng-model="MyAmount"
                            value="{{MyAmount | currency}}" />

but it is converted only for the first key I, for example, it converts 2 to $ 2.00, and then clears the value (I suppose it finds this updated value as not a number?)

: , , , $ , . .

+4
3

. ngModelController $formatters $parsers $modelValue $viewValue .

  • $modelValue currency, .

  • $viewValue ( , , ), currency $viewValue ( ).

. , , , .

{
  restrict: 'A',
  require: 'ngModel',
  link: function postLink(scope, elem, attrs, modelCtrl) {    
    modelCtrl.$formatters.push(filterFunc);
    modelCtrl.$parsers.push(function (newViewValue) {
      var newModelValue = toNumber(newViewValue);
      modelCtrl.$viewValue = filterFunc(newModelValue);
      var pos = getCaretPosition(elem[0]);
      elem.val(modelCtrl.$viewValue);
      var newPos = pos + modelCtrl.$viewValue.length -
                         newViewValue.length;
      setCaretPosition(elem[0], newPos);
      return newModelValue;
    });
  }
};

. . , . BTW, "" get/setCaretPosition() AngularUI uiMask.

+8

fcsa-number, . , fcsa-number .

<input type="text" fcsa-number />

GitHub: https://github.com/FCSAmericaDev/angular-fcsa-number

+6

, . , angular-input-masks.

ui-money-mask :

<input type="text" ng-model="money" ui-money-mask>

.

+3

Source: https://habr.com/ru/post/1541394/


All Articles