Search code examples
angularjsangularjs-directiveangularjs-filter

Angularjs number $filter directive on input requires a user to press decimal twice


I'm trying to restrict an input to only except numbers and a decimal, fix the fraction size to a max of 2, and mask the viewValue with commas, and keep the modelValue as a number. The below code almost works perfectly except in order to add a decimal, the user has to press the . key twice. Any ideas why the first press is stripping the decimal?

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>


Solution

  • It's because the number filter in AngularJS strips out the decimal when the supplied fractionSize argument is zero.

    You can confirm this yourself:

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

    So to get around it, simply apply the number filter conditionally:

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