清除数字输入类型不适用于“e”数字
当我用数字类型输入 eee 清除输入字段时,它不会被清除。任何其他输入数字都会被清除。检查 JSFiddle。任何提示将不胜感激。
<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/