输入的AngularJS数字$ filter指令要求用户按两次十进制

时间:2018-09-05 11:35:10

标签: angularjs angularjs-directive angularjs-filter

我试图将输入限制为仅数字和小数除外,将小数的大小固定为最大2,并用逗号屏蔽viewValue,并将modelValue保留为数字。下面的代码几乎可以完美地工作,除了要添加小数,用户必须按两次.键。知道为什么第一次按下会删除小数点吗?

var app = angular.module('myApp', []);
app.controller('pageCtrl', function($scope){
    $scope.myModel = 0;
});

app.directive('formatter', ['$filter', function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl || !attrs.formatter) return;
            ctrl.$formatters.unshift(function (a) {
                return $filter(attrs.formatter)(ctrl.$modelValue, 2)
            });

            ctrl.$parsers.unshift(function (viewValue) {
                var plainNumber = viewValue.replace(/[^0-9.]/g, '');
                var fractionSize = 0;
                if (plainNumber.indexOf('.') >= 0) {
                    var parts = plainNumber.split('.');
                    fractionSize = parts[1].length > 2 ? 2 : parts[1].length;
                }
                elem.val($filter(attrs.formatter)(plainNumber, fractionSize));

                return plainNumber;
            });
        }
    };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body ng-app="myApp">
   <div ng-controller="pageCtrl">
      <input formatter="number" ng-model="myModel">
      {{ myModel }}
   </div>
</body>

1 个答案:

答案 0 :(得分:0)

这是因为当提供的number参数为零时,AngularJS中的fractionSize过滤器会去除小数。

您可以自己确认:

<!-- 2 -->
{{ 2. | number:0 }}

要解决此问题,只需有条件地应用number过滤器:

elem.val(fractionSize ? $filter(attrs.formatter)(plainNumber, fractionSize) : plainNumber);