在angularjs中格式化小数点

时间:2014-12-17 10:54:29

标签: angularjs

我有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);
            }

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

1 个答案:

答案 0 :(得分:3)

您可以编写自定义指令,例如:

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/

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

相关问题