我正在尝试创建一个输入元素:
- 保存一个数字(字符串或实际数字并不重要)。
- 除了数字和点 (.) 之外,您不能输入任何其他内容。
- 您可以输入两位小数。
如果没有输入小数,则在离开输入元素(模糊时)时,应在数字中添加两位小数(即 .00)。
我正在使用 AngularJS (1.2) 并在包含的表单上观察 $valid 和 $invalid。
输入的值为两位小数且大于0的数字有效。
我尝试过使用:
<input ng-model="price" type="number" ng-blur="addDecimals()"/>
$scope.addDecimals = function(){
$scope.price = $scope.price.toFixed(2);
}
但是我无法将零添加为小数 (.00)。由于 toFixed() 返回一个字符串,因此输入中不允许有该值,因此它会变为空。
我也尝试过使用
<input type="text" ng-model="price" ng-blur="addDecimals()" ng-change="changed()" />
$scope.changed = function(){
// removes all charachters but numbers and one dot (.);
// examples:
// if value is '1a.t9' it will be changed to '1.9'
// if value is 'qwe' it will be changed to ''
// if value is 4 it will not be changed.
$scope.price = removeAllCharsButNumbersAndDot($scope.price);
}
$scope.addDecimals = function(){
if(parseFloat($scope.price) > 0)
$scope.price = $scope.price.toFixed(2);
else
$scope.price = "";
}
使用此解决方案,如果输入值“0”,[form].$valid 将设置为 true。 [form].$valid 仅当用户离开输入元素(on-blur)时才会设置为 false,这有点难看。
我尝试使用 ng-pattern="/^\s*(?=.[1-9])\d(?:.\d{1,2})?\s*$/",但是 ng-change 不会触发。
最佳答案
您可以使用https://github.com/angular-ui/ui-validate 。 Ui-validate 对此非常有用。示例:
<input type="number" ng-model="priceModel" ui-validate=" 'checkPriceModel($value)' ">
//Controller:
$scope.checkPriceModel = function(value){
return value <= 0;
}
关于javascript - AngularJS 只允许带小数的数字的输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34807853/