使用 AngularJS 在输入类型数字中强制舍入步骤
Force round step in input type number with AngularJS
在网络应用程序 (AngualrJS 1.5 + HTML5) 中,我有一个输入类型="number"。我想加入 0.5。问题是如果用户写 0.7,表单不会通知错误。如何自动将字段中的数字四舍五入?
这是 html 代码:
<input type="number" ng-model="height" name="height" min="1" max="10000" step="0.5">
我试图在保存页面时添加此 js 代码:
$scope.age = (Math.round($scope.age * 2) / 2).toFixed(1);
但我在控制台中收到此错误:
angular.js?v=0.2:13708 Error: [ngModel:numfmt] Expected `6.0` to be a number
更新:
我做了一个 plunker:PLNKR
看看下面的代码。
<body ng-app="numberExample">
<script>
angular.module('numberExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.age = 5;
$scope.roundNo = function(){
$scope.age = (Math.round($scope.age * 2) / 2);
};
$scope.save = function(){
}
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<input type="number" name="input" ng-model="age"
min="0" max="1000" step="0.5" ng-change="roundNo()" required>
</form>
<button ng-click="save()">Save</button>
</body>
工作的 plunker here
在网络应用程序 (AngualrJS 1.5 + HTML5) 中,我有一个输入类型="number"。我想加入 0.5。问题是如果用户写 0.7,表单不会通知错误。如何自动将字段中的数字四舍五入?
这是 html 代码:
<input type="number" ng-model="height" name="height" min="1" max="10000" step="0.5">
我试图在保存页面时添加此 js 代码:
$scope.age = (Math.round($scope.age * 2) / 2).toFixed(1);
但我在控制台中收到此错误:
angular.js?v=0.2:13708 Error: [ngModel:numfmt] Expected `6.0` to be a number
更新: 我做了一个 plunker:PLNKR
看看下面的代码。
<body ng-app="numberExample">
<script>
angular.module('numberExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.age = 5;
$scope.roundNo = function(){
$scope.age = (Math.round($scope.age * 2) / 2);
};
$scope.save = function(){
}
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<input type="number" name="input" ng-model="age"
min="0" max="1000" step="0.5" ng-change="roundNo()" required>
</form>
<button ng-click="save()">Save</button>
</body>
工作的 plunker here