重置HTML5“;数字“;包含在Google Chrome中使用AngularJS的文本的字段

Reset a HTML5 "number" field containing text using AngularJS in Google Chrome

本文关键字:AngularJS 文本 字段 Google 数字 HTML5 包含 重置 Chrome      更新时间:2023-09-26

用例

我有一个数字字段,上面特别写着"输入一个数字"。最终用户将始终输入一个字符串。当用户使用Google Chrome点击"重置"按钮时,包含文本的数字字段将不会重置。

要求是:

  • 用户无法按照说明进行升级:D
  • 单击重置按钮应将数字默认为未定义
  • 理想情况下,我们希望保留type="number"属性,因为它允许键盘在移动设备上弹出

代码

提供了jsFiddle演示。

角度模板

<div ng-app="app" ng-controller="ctrl">
    <p>
        Enter a string into the "number" field. Clicking any of the buttons
        will not clear the field.
    </p>
    <p>
        Enter a number into the "number" field. Clicking any of the buttons
        will clear the field.
    </p>
    <input type="number" ng-model="someValue" placeholder="Enter a number"/>
    <button type="button" ng-click="set('hello, world!')">Set to Hello, World!</button>
    <button type="button" ng-click="set(undefined)">Set to undefined</button>
    <button type="button" ng-click="set('')">Set to empty string</button>
    <button type="button" ng-click="set(0)">Set to zero</button>
</div>

Angular应用程序&控制器

angular.module('app', [])
.controller('ctrl', function($scope) {
    $scope.someValue = undefined;
    $scope.set = function(val) {
        $scope.someValue = val;
    };
});

问题

  • 如何将Angular中包含无效值的数字字段重置为未定义(或空白)

您的字段是必需的,所以对Angular说吧!

http://jsfiddle.net/TQ59f/10/

<input type="number" ng-model="someValue" required="true" placeholder="Enter a number"/>

请注意,将undefined设置为数字的值不会清除输入的数字。但是,将非数字字符串设置为值(如hello world)将清除该字段,因为它不是数字字符串。

编辑:poster mister_radize找到的指令方式似乎是AngularJS在没有"必需"的情况下解决问题的方式。

解决方案

这似乎可以通过指令来解决,但我希望有一个侵入性较小的解决方案,因为该指令会对任何输入进行触发。然而,它做了需要做的事情。在数字字段中输入字符串似乎会破坏Google Chrome和Angular的功能。

指令

.directive('input', function () {
    return {
        restrict: 'E',
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (attrs.type.toLowerCase() !== 'number') {
                return;
            } //only augment number input!
            ctrl.$formatters.push(function (value) {
                return value ? parseFloat(value) : null;
            });
        }
    };
});

我在试图清除字段时遇到了这个问题。我能够解决这个问题,首先将模型值设置为一个数字,然后在$timeout中显式地将其设置为null,这样它就会出现在$digest之后。

plunker示例

您可能可以使用类似的方法(确保注入$timeout!)。

angular.module('app', [$timeout])
.controller('ctrl', function($scope) {
    $scope.someValue = undefined;
    $scope.set = function(val) {
        $scope.someValue = 1;
        $timeout(funciton () {
            $scope.someValue = val
        });
    };
});