经过两个小时的研究和尝试,我无法清除一个插入无效值的数字输入字段。我已经尝试过将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;
};
}
这里是fiddle,在这里我还添加了一个 "setZero "函数,以显示将模型改为有效的非空输入是很好用的。https:/jsfiddle.netMcGiogenvhx87yq6
只要用Firefox打开链接,在输入栏中输入任何非数字字符串,然后按 "清除输入 "按钮。什么都不会发生。
你可以尝试使用一个输入文本,并通过自定义指令来验证用户输入。
请看这个链接以获得更好的解释。
如果你想允许输入+和-,请用类似的东西修改regex。
[^0-9\-\.\+]
当涉及到输入字段时,跨浏览器之间有很多问题。这里有一篇文章可以给你所有你需要的信息。
https:/css-tricks.comnumeric-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>
用''代替null
function MyCtrl($scope) {
$scope.numberModel = null;
$scope.clearInput = function() {
$scope.numberModel = '';
};
$scope.setZero = function() {
$scope.numberModel = 0;
};
}