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



清除数字输入类型不适用于'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 = "";
};
});

<input type="number">元素的内容解析为NaN(不是数字(时,ng-model指令无法清除该元素的内容。当用户粘贴无效内容或简单地键入"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" />

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>

最新更新