Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在Angularjs中格式化输入值_Javascript_Jquery_Angularjs_Input - Fatal编程技术网

Javascript 在Angularjs中格式化输入值

Javascript 在Angularjs中格式化输入值,javascript,jquery,angularjs,input,Javascript,Jquery,Angularjs,Input,我正在尝试编写一个指令,自动格式化中的数字,但模型没有格式化。 让它正常工作很好,加载时,输入中的值在控制器中显示为1000000和1000000,但是当仅键入ngModel时,$parsers函数将启动。 ngModel.$formatters触发的唯一时间是在加载指令时以及值为0时 如何使它在keypress上工作(我尝试绑定到keypress/keypup,但不起作用) 这是我的密码: angular.module('myApp.directives', []).directive('fi

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

如何使它在keypress上工作(我尝试绑定到keypress/keypup,但不起作用)

这是我的密码:

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 || ''));
            });

        }
    };
}]);

下面是使用
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" />

请参见演示


希望它的帮助

根据此问题的答案,对Maxim Shoustin的回答进行小编辑:

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

   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 '';
        }
    });

这个模块对我来说很好

例如:

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

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

  • 将焦点上的输入初始化为0.00
  • 与模板驱动和反应形式兼容
  • 删除/撤消任何非数字项
  • 防止空输入
  • 粘贴123ab4d5,输出:12345
  • 每千除以一
  • 退格/删除兼容
  • 让我们在中间输入/删除。
  • 仅限正整数
  • 推荐的:使用[maxLength]将用户限制在特定长度

     <input [maxLength]="9" appPriceUsd>
    

    希望能有帮助。喜欢编码。

    如果我想添加150.33这样的小数点,我需要按两次“.”。为什么呢?无论如何要“修复”它吗?您将如何使用
    ?我试过了,但失败了:我喜欢你所做的解决方案,我有一个问题是有一个表达式可以用“.”(点)代替“,”(逗号),因为它在欧洲的默认值是“.”(点)是千位分隔符,“,”(逗号)是十进制分隔符?@Clark--
    push
    放在数组的末尾,
    在数组开始时取消移位
    。因为$parsers,函数是“按数组顺序”执行的,而$formatters是“按相反的数组顺序”执行的。当您在一行中键入两次相同的字母表时,它确实会失败。您可以看到解析不会触发的字母表;我仍然得到0。如何从空白输入框开始?它看起来不错,尽管它使用的方法与公认答案中描述的方法相同。而且,当被问到这个问题时,这个问题并不存在。
    // 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');
      }
    }