以角度格式设置小数点的格式



我有大约 10 个文本框,如果用户输入 10.3691,那么它应该更改为 10.37

<input ng-model='data.value1' ng-blur="formatDecimals1()">
<input ng-model='data.value2' ng-blur="formatDecimals2()">
......

在控制器中,

$scope.formatDecimals1 = function() {                
                $scope.data.value1= Number($scope.data.value1).toFixed($scope.data.value1Points);
            }
$scope.formatDecimals2 = function() {                
                $scope.data.value2= Number($scope.data.value2).toFixed($scope.data.value2Points);
            }

我觉得这不是一个正确的方式...任何其他解决方案都可以实现这一目标。或者,我们如何使用单个通用函数来格式化所有文本框输入。

您可以编写一个自定义指令,如下所示:

angular.module('app', []).
directive('toPrecision', function(){
    return {
        replace: false,
        restrict: 'A',
        link: function(scope, element) {
            var e = angular.element(element);
            e.on('keyup', function(){
                var n = parseFloat(e.val());
                if (parseInt(n, 10) !== n && String(n).split('.')[1].length > 2) {
                    e.val(n.toFixed(2));
                }
            });
        }
    }
});

然后在标记中:

<div ng-app="app">
    <input type="number" to-precision="2" />
</div>

您可以在此处尝试工作代码:http://jsfiddle.net/ctgxd4va/

附言。我在 2 分钟内写好了,它远非完美......但它应该给你一个想法;)

最新更新