【问题标题】:Force round step in input type number with AngularJS使用AngularJS强制输入类型编号
【发布时间】:2016-09-21 10:53:53
【问题描述】:

在网络应用程序(AngualrJS 1.5 + HTML5)中,我有一个输入类型 =“数字”。我想步入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

【问题讨论】:

  • jsFiddle 之类的?
  • 看起来你正在为模型分配字符串,但它应该是数字。试试 parseFloat(yourmodel)
  • 我已经做了一个plunker

标签: javascript angularjs html input rounding


【解决方案1】:

看看下面的代码。

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

打工仔here

【讨论】:

    猜你喜欢
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2015-04-13
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    相关资源
    最近更新 更多