在 Angularjs 中格式化输入值

IT技术 javascript jquery angularjs input
2021-03-02 03:06:03

我正在尝试编写一个指令来自动格式化一个数字,<input>但模型没有被格式化。让它工作很好,加载时输入中的值在控制器中显示为 1,000,000 和 1000000,但是当只输入ngModel.$parsers函数时会触发。唯一ngModel.$formatters发生火灾的时间是指令被加载并且值为 0 时。

我怎样才能让它在 keypress 上工作(我已经尝试绑定到 keypress/keyup 但它不起作用)。

这是我的代码:

angular.module('myApp.directives', []).directive('filterInput', ['$filter', function($filter) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {

            ngModel.$parsers.push(function fromUser(text) {
                return parseInt(text.replace(",", ""));
            });

            ngModel.$formatters.push(function toUser(text) {
                console.log($filter('number')(text));
                return ($filter('number')(text || ''));
            });

        }
    };
}]);
4个回答

这是我们使用的工作示例unshift

angular.module('myApp.directives', []).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) {
                var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
                elem.val($filter(attrs.format)(plainNumber));
                return plainNumber;
            });
        }
    };
}]);

HTML似乎:

<input type="text" ng-model="test" format="number" />

看演示 Fiddle

希望它的帮助

您将如何使用<input type="number">? 我试过了,但失败了:jsfiddle.net/SAWsA/3957
2021-04-21 03:06:03
我喜欢你所做的解决方案,我有一个问题是有一个表达式可以用“。”(点)代替“,”(逗号),因为它在欧洲的默认值是“。”(点)是一个千位分隔符和“,”(逗号)是小数分隔符?
2021-04-22 03:06:03
当您连续两次键入相同的字母表时,它确实会失败。您可以看到解析未触发的字母表。
2021-04-24 03:06:03
如果我想添加一个像 150.33 这样的小数点,我需要按 '.' 两次。这是为什么?无论如何要“修复”它?
2021-04-28 03:06:03
@Clark——push放在数组的末尾unshift放在数组的开头顺序很重要,因为$解析器,函数是“在阵列令”执行,但$“在格式化,反向排列顺序”。
2021-05-01 03:06:03

这个module对我来说很好用。

https://github.com/assisrafael/angular-input-masks

例子:

<input type="text" name="field" ng-model="number" ui-number-mask>
它看起来不错,尽管它使用了已接受的答案中描述的相同方法。当提出问题时,这也不在身边。
2021-04-27 03:06:03

根据对这个问题的回答,对下面的 Maxim Shoustin 的回答进行了小编辑: AngularJS 格式化程序 - 如何显示空白而不是零

唯一的变化是确保在删除最后一个数字时输入为空白而不是零:

   ctrl.$parsers.unshift(function (viewValue) {
        console.log(viewValue);
        if(viewValue){
            var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
            elem.val($filter('number')(plainNumber));
            return plainNumber;
        }else{
            return '';
        }
    });

http://jsfiddle.net/2n73j6rb/

如果我以 $scope.test = ''; 开头 我仍然得到 0。如何从空白输入框开始?jsfiddle.net/magician11/947cb12h
2021-05-17 03:06:03

我为自己创建了这个指令解决方案,它可以:

  1. 在焦点上将输入初始化为 0.00。
  2. 与模板驱动和 ReactiveForm 兼容。
  3. 删除/撤消任何非数字条目。
  4. 防止空输入。
  5. 粘贴 123ab4d5,输出:12345。
  6. 每千除以 a ,
  7. 退格/删除兼容。
  8. 让我们在中间输入/删除。
  9. 仅正整数。

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

推荐:使用 [maxLength] 将用户限制为一定长度。

 <input [maxLength]="9" appPriceUsd>

这是指令:

// Format USD by Reza Taba
import { DecimalPipe } from '@angular/common';
import { Directive, ElementRef, HostListener } from '@angular/core';


@Directive({
  selector: '[appPriceUsd]'
})
export class PriceUsdDirective {
  constructor(private elRef: ElementRef, private decimalPipe: DecimalPipe) { }

  @HostListener('focus') initializeValue(): void {
    if (this.elRef.nativeElement.value === '') {
      this.elRef.nativeElement.value = '0.00';
    }
  }

  @HostListener('keyup') formatUsd(): void {
    let value: string;
    value = this.elRef.nativeElement.value as string;
    value = this.removeNonDigtis(value); // remove all non-digit values
    value = this.addDecimalPoint(value); // Add . to the -2 index
    value = this.applyDecimalPipe(value); // to divide every thousand
    this.elRef.nativeElement.value = value;
  }

  removeNonDigtis(value: string): string {
    let inputArray: string[] = [];
    const digitArray: string[] = [];

    // 12a34b to ["1", "2", "a", "3", "4", "b"]
    inputArray = value.split('');

    // remove any non-digit value
    for (const iterator of inputArray) {
      if (/[0-9]/.test(iterator)) {
        digitArray.push(iterator);
      }
    }

    return digitArray.join('');
  }

  addDecimalPoint(value: string): string {
    const inputArray = value.split(''); // ['0', '.', '0', '0']
    inputArray.splice(-2, 0, '.'); // place decimal in -2
    return inputArray.join('');
  }

  applyDecimalPipe(value: string): string {
    console.log(value);
    return value === '' || value === '.'
      ? '0.00'
      : this.decimalPipe.transform(value, '1.2-2');
  }
}

希望能帮助到你。享受编码。