【问题标题】:dynamically change input type number decimal places动态更改输入类型数字小数位
【发布时间】:2018-09-08 12:10:01
【问题描述】:

我有一个表格和该表格中的一些输入类型编号。

我需要将用户输入值动态四舍五入到某个可配置的精度(来自服务器,存在于 ngmodel 中,如 ct.precision)。我的输入值可能是 '' 取决于初始值。

我正在尝试使用过滤器编号,但我不确定我是否应该这样使用它。 我尝试使用 onChange,但无法使用可配置值设置精度。

实现这一目标的最佳方法是什么?

<input
    id="quantityValue-{{ $index }}"
    class="my-quantity"
    ng-model="$ct.record[$index].newQuantity"
    type="number"
    required
    min="0"
    pattern="\d+(\.\d+)?"
    maxlength="15"
>

这就是我的输入的样子。

【问题讨论】:

    标签: html angularjs input angular-filters


    【解决方案1】:

    尝试在输入字段和可配置的精度选择上使用ng-change不管是什么,我选择了&lt;select&gt;)。这是一个没有验证的演示:

    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $filter) {
      $scope.foo = function(x, n = 3) {
        $scope.x_ = Number($filter('number')(x, n));
      }
      $scope.precision = [0, 1, 2, 3, 4, 5];
      $scope.n = $scope.precision[0]; // default (optional)
      $scope.x = 0; // default (to remove NaN issues)
      $scope.foo($scope.x, $scope.n); // initialise precision
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    
    <div ng-app="myApp" ng-controller="myCtrl">
      <select ng-model="n" ng-change="foo(x,n)" ng-options="p for p in precision">
    </select>
      <hr>
      <input type="number" ng-model="x" ng-change="foo(x,n)">
      <br>{{x_}}
    </div>

    (舍入可能存在一些问题(责备 JavaScript),其中舍入 0.129999 得到 0.13 的精度在 2 到 5 之间)

    【讨论】:

    • 感谢您的建议,但我实际上需要它来强制输入具有精度,而不是显示值来显示它..
    • @solarapricot 然后将所有x_ 重命名为x,它只会阻止您输入更多数字(而不是尝试向上取整)
    • x.toFixed(n) 代替$filter('number')(x, n) 会更好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    相关资源
    最近更新 更多