【问题标题】:Firefox can't clear invalid number field with AngularFirefox 无法使用 Angular 清除无效数字字段
【发布时间】:2015-12-15 11:18:01
【问题描述】:

经过两个小时的研究和尝试,当插入无效值时,我无法清除数字输入字段。我已经尝试将 ng-model 设置为 null、undefined 和 '' 但没有一个有效。

只有 Firefox 有这个问题,我在最新版本的 Chrome 和 IE 上测试过。

我的简化代码是:

HTML

<div ng-controller="MyCtrl">
  <form name="frmToClear">
    <input type="number" name="numField" ng-model="numberModel">
  </form>
  <button ng-click="clearInput()">Clear input</button>
</div>

Javascript

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.numberModel = null;

    $scope.clearInput = function() {
        $scope.numberModel = null;
    };
}

这是我还添加了一个“setZero”函数的小提琴,以表明将模型更改为有效的非空输入运行良好:https://jsfiddle.net/McGiogen/vhx87yq6/

重现

错误只是用 Firefox 打开链接,在输入字段中写入任何非数字字符串,然后按“清除输入”按钮。什么都不会发生。

经过测试的浏览器:

  • 火狐40.0.3
  • Firefox 开发版 42.0a2
  • 铬 45.0.2454.93
  • IE 11.0.9600.17959

【问题讨论】:

    标签: angularjs input numbers reset


    【解决方案1】:

    您可以尝试使用输入文本并通过自定义指令验证用户输入。

    查看此链接以获得更好的解释:

    How to allow only a number (digits and decimal point) to be typed in an input?

    如果你想允许 + 和 - 用类似的东西修改正则表达式:

    [^0-9\-\.\+]
    

    【讨论】:

    • 我认为这是一个 Firefox 错误,所以正如 @cullimorer 所说,这可能是临时解决此问题的正确解决方法。
    【解决方案2】:

    在涉及输入字段时,跨浏览器之间存在许多问题。这篇文章可以为您提供所需的所有信息。

    https://css-tricks.com/numeric-inputs-a-comparison-of-browser-defaults/

    我会通过向用户显示一条消息告诉他们输入一个有效数字然后使用 Angular 的内置验证来防止错误输入来解决这个问题。

    <div ng-controller="MyCtrl">
      <form name="frmToClear">
        <input required type="number" name="numField" ng-model="numberModel">
      </form>
      <div ng-show="!frmToClear.$valid">Please enter a valid number only</div>
      <button ng-click="clearInput()" ng-disabled="!frmToClear.$valid">Clear input</button>
      <button ng-click="setZero()" ng-disabled="!frmToClear.$valid">Set zero</button>
    </div>
    

    【讨论】:

      【解决方案3】:

      用''代替null

      function MyCtrl($scope) {
          $scope.numberModel = null;
      
          $scope.clearInput = function() {
              $scope.numberModel = '';
          };
      
          $scope.setZero = function() {
             $scope.numberModel = 0;
          };
      }
      

      【讨论】:

      • 很抱歉,我已经尝试过这个解决方案,但它不起作用
      • 不清楚输入是否有字符串而不是数字,因为它有错误,但如果你有正确的数字,它会将其设置为空。
      • 我在小提琴上查过了
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 2017-05-30
      • 2018-01-20
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 2023-01-16
      相关资源
      最近更新 更多