简体   繁体   中英

Force round step in input type number with AngularJS

In a web app (AngualrJS 1.5 + HTML5) I have an input type="number". I want to step in 0.5. The problem is that if the user write 0.7, the form doesn't notificate the error. How can I do to automatic round the number in the field?

This is the html code:

 <input type="number" ng-model="height" name="height" min="1" max="10000" step="0.5">

I've tried to add this js code when I save the page:

$scope.age = (Math.round($scope.age * 2) / 2).toFixed(1);

but I get this error in console:

angular.js?v=0.2:13708 Error: [ngModel:numfmt] Expected `6.0` to be a number

UPDATE: I've made a plunker: PLNKR

Have a look into below code.

<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>

Working plunker here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM