在Angularjs中格式化输入值

时间:2013-11-10 13:39:09

标签: javascript jquery angularjs input

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

如何让它在按键上运行(我尝试绑定到按键/键盘,但它不起作用)。

这是我的代码:

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 个答案:

答案 0 :(得分:50)

以下是我们使用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

希望得到帮助

答案 1 :(得分:5)

这个模块对我来说很好。

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

示例:

<input type="text" name="field" ng-model="number" ui-number-mask>

答案 2 :(得分:1)

根据这个问题的答案,对Maxim Shoustin的答案进行小编辑: AngularJS formatter - how to display blank instead of zero

仅更改是为了确保在删除最后一个数字时输入为空而不是零:

   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/

答案 3 :(得分:0)

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

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

enter image description here

enter image description here

enter image description here

推荐:使用 [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');
  }
}

希望有帮助。享受编码。