codememo

통화 마스크 지시문이 있는 모서리 입력 필드(즉각 화폐 형식)

tipmemo 2023. 3. 29. 21:32
반응형

통화 마스크 지시문이 있는 모서리 입력 필드(즉각 화폐 형식)

http://jquerypriceformat.com/을 사용하여 EU 머니 필드의 입력 마스크를 작성하려고 합니다.

지금까지의 지시에서는, 마스크가 적용되고 있는 유저에게는 입력이 올바르게 표시되고 있습니다만, 뭔가 잘못된 것 같습니다.왜냐하면 POST 값이 입력 필드에 표시되어 있는 것과 전혀 다른 형식으로 송신되고 있기 때문입니다.

가격 포맷을 첨부합니다.js

<script src="js/jquery.price_format.1.8.min.js"></script>

<input type="text" currency-input ng-model...>

그리고 각도:

app.directive('currencyInput', function() {
    return {
      require: '?ngModel',
      link: function($scope, element, attrs, controller) {
        element.priceFormat({
            prefix: '',
            centsSeparator: ',',
            thousandsSeparator: '.'
        });
      }
    };
});

입력은 마스크와 함께 값을 올바르게 표시하지만 POST 데이터(각도로 호출)에서는 다른 값입니다.누락되어 있는 것은 무엇입니까?

입력 > 2.200,80 | 포스트 > 22,0080

감사해요.

이 예에서 링크는 무언가를 반환하지 않습니다.

나는 다음과 같은 지시문을 쓸 것이다.

.directive('format', ['$filter', function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;


            ctrl.$formatters.unshift(function (a) {
                return $filter(attrs.format)(ctrl.$modelValue)
            });


            ctrl.$parsers.unshift(function (viewValue) {

          elem.priceFormat({
            prefix: '',
            centsSeparator: ',',
            thousandsSeparator: '.'
        });                

                return elem[0].value;
            });
        }
    };
}]);

데모 1

여기에 이미지 설명 입력

시작 시 필터를 작동시키려면$formatters:

지금이다link다음과 같습니다.

link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;

            var format = {
                    prefix: '',
                    centsSeparator: ',',
                    thousandsSeparator: ''
                };

            ctrl.$parsers.unshift(function (value) {
                elem.priceFormat(format);

                return elem[0].value;
            });

            ctrl.$formatters.unshift(function (value) {
                elem[0].value = ctrl.$modelValue * 100 ;
                elem.priceFormat(format);
                return elem[0].value;
            })
        }

데모 2

푸시 a$parser를 사용하여 값이 입력과 일치하지 않을 때만 값을 갱신합니다.$setViewValue()그리고.$render().

app.directive('currencyInput', function() {
    return {
      require: '?ngModel',
      link: function($scope, element, attrs, controller) {
        return ctrl.$parsers.push(function(inputValue) {

            ...

            if (result != inputValue) {
                controller.$setViewValue(res);
                controller.$render();
            }
        });
      }
    };
});

여기 내 통화 입력 지침에서 사용한 논리가 있다: 바이올린

파티에 늦었지만, 다른 대답을 들을 만 하다고 생각해요!ng-currency 모듈을 사용하고 있습니다.정말 환상적이에요.

나는 두빌라의 접근법이 단순하고 우아해서 좋다.그 위에 (적절한 크레딧이 있는) 기능을 추가하여 실제 사용 사례에 매우 가깝게 만들기로 했습니다.

유용한 금융지침을 작성하기 위해 github 프로젝트에 사용하고 있습니다.

주목할 만한 추가 기능:

  1. 유효한 응답을 하기 위해 입력에 대한 엄격한 체크를 수행합니다.
  2. 큰 숫자를 더 빨리 입력할 수 있도록 몇 가지 바로 가기 키가 있습니다.
  3. 부트스트랩 및 ngmodel css 업데이트와 통합하는 방법을 보여 줍니다.
  4. 보너스로 폼의 ngmonel을 JSON으로 출력하여 폼의 유효성을 실시간으로 확인할 수 있도록 하였습니다.

또한 ng모델로서 POJO를 사용합니다.

function Money() {
    this.notional = 0;
    this.maxValue = 99999999999.9;
    this.maxValueString = "99,999,999,999.9";
    this.maxPrecision = 10;
}

다음과 같이 Bootstrap 3과 함께 사용할 수 있습니다.

<h1>Currency Formatting directive</h1>

<div class="row">

    <div class="col-md-6">
        <form name="myForm">

            <div class="form-group" ng-class="{'has-error': myForm.notional.$invalid && myForm.notional.$touched}">
                <input type="text" ng-model="myForm.money.notional  " money="money" money-input size="30" required
                       name="notional"
                       class="form-control"
                       placeholder="Enter notional amount"/>

                      <p class="help-block error" ng-show="myForm.notional.$error.required && myForm.notional.$touched">Required</p>



            </div>

            <button ng-disabled="myForm.$invalid" type="submit">SAVE</button>
        </form>
        <h2>Tips</h2>
        <ol>

            <li> Entering 'k' will multiply the amount by one thousand</li>
            <li> Entering 'm' will multiply the amount by one million</li>
            <li> Entering 'b' will multiply the amount by one billion</li>
        </ol>
    </div>
</div>
<p>Form debugger</p>
<pre>
               form = {{ myForm | json }}
    </pre>

다음은 Angular 지시어만 사용하여 jQuery 없이 이 문제를 처리하는 방법입니다.이 예에서는 소수점을 지원하지 않습니다.이를 지원하기 위해 수정하는 것은 간단합니다만,$filter에서toView()기능.

작성자가 언급한 jQuery와 통화 플러그인으로 로드되는 것을 피할 수 있기 때문에, 같은 문제를 해결하는 것이 더 좋은 방법이라고 생각합니다.Euro에 대한 로케일 지원은 다음 명령어를 사용하여 지원되어야 합니다.$locale속성입니다만, 이것은 USD로만 테스트하고 있습니다.

(function() {
  var app = angular.module('currencyMask', []);

  // Controller
  app.controller('ctrl', ['$scope', function($scope) {
    $scope.amount = 100000;
  }]);

  // Directive
  app.directive('inputCurrency', ['$locale', '$filter', function($locale, $filter) {

    // For input validation
    var isValid = function(val) {
      return angular.isNumber(val) && !isNaN(val);
    };

    // Helper for creating RegExp's
    var toRegExp = function(val) {
      var escaped = val.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
      return new RegExp(escaped, 'g');
    };

    // Saved to your $scope/model
    var toModel = function(val) {

      // Locale currency support
      var decimal = toRegExp($locale.NUMBER_FORMATS.DECIMAL_SEP);
      var group = toRegExp($locale.NUMBER_FORMATS.GROUP_SEP);
      var currency = toRegExp($locale.NUMBER_FORMATS.CURRENCY_SYM);

      // Strip currency related characters from string
      val = val.replace(decimal, '').replace(group, '').replace(currency, '').trim();

      return parseInt(val, 10);
    };

    // Displayed in the input to users
    var toView = function(val) {
      return $filter('currency')(val, '$', 0);
    };

    // Link to DOM
    var link = function($scope, $element, $attrs, $ngModel) {
      $ngModel.$formatters.push(toView);
      $ngModel.$parsers.push(toModel);
      $ngModel.$validators.currency = isValid;

      $element.on('keyup', function() {
        $ngModel.$viewValue = toView($ngModel.$modelValue);
        $ngModel.$render();
      });
    };

    return {
      restrict: 'A',
      require: 'ngModel',
      link: link
    };
  }]);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>

<div ng-app="currencyMask" ng-controller="ctrl">
	<input input-currency ng-model="amount">
	<p><strong>Amount:</strong> {{ amount }}</p>
</div>

언급URL : https://stackoverflow.com/questions/19576202/angular-input-field-with-a-currency-mask-directive-for-money-format-on-the-fly

반응형