用于货币的角度过滤器,允许输入负数

时间:2016-07-12 16:36:47

标签: angularjs filter format currency angular-directive

我有一个指令,通过在用户输入时添加小数点来过滤货币。

我的问题是它不会允许否定。允许用户输入“ - ”符号并将其始终显示在数字的开头,或输入“+”并让它消失,这将是一件好事。

需要:

  1. 将十进制字段格式化为用户类型
  2. 字段必须是数字
  3. 必须允许否定-
  4. 允许0.00作为数字输入
  5. Check out my Plunker here。它有input = number但不允许负数:

    app.directive('format', ['$filter', function ($filter) {
        return {
            require: 'ngModel', //there must be ng-model in the html
            link: function (scope, elem, attr, ctrl) {
                if (!ctrl) return;
    
                ctrl.$parsers.unshift(function (viewValue, modelValue) {
                    var plainNumber = viewValue.replace(/[^-+0-9]/g,'');
    
                    // use angular internal 'number' filter
                    plainNumber = $filter('number')(plainNumber / 100, 2).replace(/,/g, '');
    
                    // update the $viewValue
                    ctrl.$setViewValue(plainNumber);
    
                    // reflect on the DOM element
                    ctrl.$render();
    
                    // return the modified value to next parser
                    return plainNumber;
                });
            }
        };
    }]);
    

1 个答案:

答案 0 :(得分:1)

这将完全按照您的意愿行事:

var app = angular.module('App',[]);

 app.controller('MainCtrl', function ($scope) {


});

 app.directive('format', ['$filter', function ($filter) {
 return {
            require: 'ngModel', //there must be ng-model in the html
            link: function (scope, elem, attr, ctrl) {
                if (!ctrl) return;

                ctrl.$parsers.unshift(function (viewValue, modelValue) {
                    var plainNumber = viewValue.replace(/[^-+0-9]/g,'');
                    var newVal = plainNumber.charAt(plainNumber.length-1);
                    var positive = plainNumber.charAt(0) != '-';
                    if(isNaN(plainNumber.charAt(plainNumber.length-1))){
                      plainNumber = plainNumber.substr(0,plainNumber.length-1)
                    }
                    //use angular internal 'number' filter
                    plainNumber = $filter('number')(plainNumber / 100, 2).replace(/,/g, '');
                    if(positive && newVal == '-'){
                      plainNumber = '-' + plainNumber;
                    }
                    else if(!positive && newVal == '+'){
                      plainNumber = plainNumber.substr(1);
                    }
                    plainNumber.replace('.', ',');
                    //update the $viewValue
                    ctrl.$setViewValue(plainNumber);
                    //reflect on the DOM element
                    ctrl.$render();
                    //return the modified value to next parser
                    return plainNumber;
                });
            }
        };

}]);

只需删除type ="数字"从:

<input ng-model="amount" format="number" />