AngularJS - 输入类型 ="number"对于非数字 (NaN) 不可清除

标签 angularjs angularjs-scope angularjs-ng-model

清除数字输入类型不适用于“e”数字

当我用数字类型输入 eee 清除输入字段时,它不会被清除。任何其他输入数字都会被清除。检查 JSFiddle。任何提示将不胜感激。

http://jsfiddle.net/2ankx9up/

<div ng-app="app">
   <div ng-controller="MainCtrl">
    <input type="number" class="form-control" data-ng-model="searchAll"> 
    </input> 
    <a class="clear" href="" data-ng-click="clearSearch()">X</a>
   </div>
</div>
var app = angular.module("app", []);
 app.controller("MainCtrl", function ($scope) {
    $scope.searchAll = "";
    $scope.clearSearch = function () {
       $scope.searchAll = "";
    };
});

最佳答案

ng-model指令无法清除 <input type="number"> 的内容当该内容解析为 NaN 时的元素(不是数字)。当用户粘贴无效内容或仅键入“eee”时,可能会发生这种情况。

一个修复方法是添加自定义指令:

app.directive('clearNan', function() {
  return {
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModel) {
      ngModel.$formatters.push(function(value) {
        if (!value) elem.val(null);
        return value;
      });
    }
  };
})

用法:

<input type="number" clear-nan ng-model="x" />

The DEMO

angular.module('numfmt-error-module', [])
.directive('clearNan', function() {
  return {
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModel) {
      ngModel.$formatters.push(function(value) {
        if (!value) elem.val(null);
        return value;
      });
    }
  };
})
.run(function($rootScope) {
  $rootScope.typeOf = function(value) {
    return typeof value;
  };
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="numfmt-error-module">
  <input clear-nan type="number" ng-model="x" />
  <br>
  {{ x }} : {{ typeOf(x) }}
  <br>
  <button ng-click="x=''">Clear input</button>
</body>

关于AngularJS - 输入类型 ="number"对于非数字 (NaN) 不可清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51643527/

相关文章:

angularjs - 使用 interpolate 和 transclude 生成表

angularjs - 如何在 AngularJs 中的指令内修改范围

javascript - 如何在 Angular JS 中提交表单时获取输入字段的标签

android - 如何添加侧抽屉? [Nativescript + Angular]

javascript - 使用 Jasmine 进行 http post 方法的单元测试用例

javascript - 将已解决的 promise 注入(inject)服务

javascript - ng-model - 空输入返回 null

javascript - 在 AngularJS 中更改不同状态的动画

javascript - ng-bind-html 中的 Angular 命令

javascript - AngularJS:ng-repeat 中的 ng-model setter