用例
我有一个数字字段,专门写着“输入一个数字”。最终用户总是会输入一个字符串。当用户使用 Google Chrome 点击“重置”按钮时,包含文本的数字字段不会重置。
要求是:
- 无法升级用户以遵循说明。 :D
- 单击重置按钮应将默认数字恢复为未定义。
- 理想情况下,我们希望保留
type="number"
属性,因为它允许键盘在移动设备上弹出。
代码
A jsFiddle演示可用。
Angular 模板
<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 应用程序和 Controller
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.someValue = undefined;
$scope.set = function(val) {
$scope.someValue = val;
};
});
问题
- 如何在 Angular 中将包含无效值的数字字段重置为未定义(或空白)?
最佳答案
您的字段是必需的,所以请告诉 Angular!
<input type="number" ng-model="someValue" required="true" placeholder="Enter a number"/>
请注意,将 undefined
设置为您的数字值不会清除数字输入。但是,将非数字字符串设置为值(如 hello world
)将清除该字段,因为它不是数字。
编辑:海报 mister_rampage 发现的指令方式似乎是 AngularJS 解决问题的方式,无需“必需”。
关于javascript - 在 Google Chrome 中使用 AngularJS 重置包含文本的 HTML5 "number"字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23087930/