Angular, input field with a currency mask directive for money format on the fly

前端 未结 5 1881
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 18:10

I\'m trying to create an input mask for a EU money field using http://jquerypriceformat.com/

So far in my directive, the input shows correctly to the user with the

5条回答
  •  难免孤独
    2020-12-04 18:53

    Here's a way to handle this without jQuery using only an Angular directive. This example doesn't support decimals. It's easy to modify it to support that though, just change the $filter in the toView() function.

    In my opinion this is a better approach to solve the same problem, as you can avoid loading in jQuery and the currency plugin mentioned by the author. Locale support for Euro should be supported by the use the $locale properties, but I've only tested this for use in 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
        };
      }]);
    })();
    
    
    

    Amount: {{ amount }}

提交回复
热议问题