panagulis72 panagulis72 - 1 year ago 100
AngularJS Question

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

I've made a plunker: PLNKR

Answer Source

Have a look into below code.

<body ng-app="numberExample">
  angular.module('numberExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.age = 5;
      $scope.roundNo = function(){
        $scope.age = (Math.round($scope.age * 2) / 2);
      $ = function(){
<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>

 <button ng-click="save()">Save</button>

Working plunker here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download