14

我看到了这个解决方案http://jsfiddle.net/gronky/GnTDJ/并且它有效。即当你输入25时,它被推回模型为0.25

HTML:

<script type="text/javascript" ng:autobind
        src="http://code.angularjs.org/0.9.17/angular-0.9.17.js"></script>
<script>
function Main() {
    this.var = '1.0000';
}
</script>
<div ng:controller="Main">
    <input type="text" name="var" ng:format="percent">
    <pre>var = {{var|json}}</pre>
</div>​

JavaScript:

angular.formatter('percent', {
  parse: function(value) {
    var m = value.match(/^(\d+)\/(\d+)/);
    if (m != null)
      return angular.filter.number(parseInt(m[1])/parseInt(m[2]), 2);
    return angular.filter.number(parseFloat(value)/100, 2);
  },
  format: function(value) {
    return angular.filter.number(parseFloat(value)*100, 0);
  },
});
​

我试着让它在最新的 AngularJS 上工作,虽然http://jsfiddle.net/TrJcB/它不再工作了,也就是说,当你输入 25 时,它也被推回为 25,它不会推送正确的 0.25模型的价值。

或者也许已经有一个内置的百分比格式化程序?我也想要货币格式化程序,或者逗号分隔的数字。

4

4 回答 4

36

实现百分比过滤器的另一种方法(使用 angular#~1.2):

angular.module('moduleName')
.filter('percentage', ['$filter', function($filter) {
    return function(input, decimals) {
        return $filter('number')(input*100, decimals)+'%';
    };
}]);

如何使用它:

<span>{{someNumber | percentage:2}}</span>
于 2014-02-12T12:19:26.233 回答
24

该小提琴不适用于当前的 Angular 版本,因为此后有很多 API 发生了变化。angular.formatter不再可用,也不再可用angular.filter

现在编写它的方法是使用指令并在指令控制器上使用$parser和可用。$formatter所以你的链接功能看起来像

link: function(scope, ele, attr, ctrl){
        ctrl.$parsers.unshift(
            function(viewValue){
                return $filter('number')(parseFloat(viewValue)/100, 2);
            }
        );
        ctrl.$formatters.unshift(
            function(modelValue){
                return $filter('number')(parseFloat(modelValue)*100, 2);
            }
        );
      }

现在也可以通过$filter服务访问过滤器。您可以在此处找到文档:https ://docs.angularjs.org/api/ng/filter/number

更新了原始示例的小提琴:http: //jsfiddle.net/abhaga/DdeCZ/18/

货币过滤器已经在 Angular 中可用:https ://docs.angularjs.org/api/ng/filter/currency

于 2012-12-02T16:51:31.917 回答
2

这是一个完整的指令,它将对输入进行解析、格式化和执行 Angular 验证。(针对角度 1.2 和 1.3 进行测试。)

我们使用它,以便我们与服务器之间的数据模型可以用十进制表示法 (0.7634) 表示,但我们向用户提供人类可读的格式 (76.34),并强制执行最大精度。请注意,该指令仅关注数字方面。我发现单独在模板中插入“%”比在此处包含它更容易。

它默认强制执行从 -100 到 100 的输入值,但您可以使用 attrspct-minpct-max.

'use strict';

angular.module('XLDirectives')
  .directive('xlPercentage', function($filter) {
    // A directive for both formatting and properly validating a percentage value. 
    // Assumes that our internal model is expressed as floats -1 to +1: .099 is 9.9%
    // Formats display into percents 1-100, and parses user inputs down to the model. 
    // Parses user input as floats between 0 and 100 into floats less than 1. 
    // Validates user input to be within the range -100 to +100. 
    // Sets Angular $valid property accordingly on the ngModelController.
    // If a `pct-max` or `pct-min` attribute is specified on the <input>, will use those bounds instead.
    // If a `pct-decimals` attr present, will truncate inputs accordingly. 

    function outputFormatter(modelValue, decimals) {
      var length = decimals || 2;
      if (modelValue != null) {
        return $filter('number')(parseFloat(modelValue) * 100, length);
      } else {
        return undefined;
      }
    };

    function inputParser(viewValue, decimals) {
      var length = decimals || 4;
      if (viewValue != null) {
        return $filter('number')(parseFloat(viewValue) / 100, length);
      } else {
        return undefined;
      }

    }

    function isWithinBounds(value, upper, lower) {
      if (value >= lower && value <= upper) {
        return true;
      } else {
        return false;
      }
    }

    return {
      restrict: 'A',
      require: 'ngModel',
      link: function postLink(scope, element, attrs, ctrl) {
        ctrl.$parsers.unshift(function(viewValue) {
          // confirm the input from the view contains numbers, before parsing
          var numericStatus = viewValue.match(/(\d+)/),
            min = parseFloat(attrs.pctMin) || -100,
            max = parseFloat(attrs.pctMax) || 100,
            decimals = parseFloat(attrs.pctDecimals) || 4,
            bounded = isWithinBounds(viewValue, max, min);
          if (numericStatus !== null && bounded) {
            ctrl.$setValidity('percentage', true);
            // round to max four digits after decimal
            return inputParser(viewValue, decimals);
          } else {
            ctrl.$setValidity('percentage', false);
            return undefined
          }
        });

        ctrl.$formatters.unshift(outputFormatter);
        // we have to watch for changes, and run the formatter again afterwards
        element.on('change', function(e) {
          var element = e.target;
          element.value = outputFormatter(ctrl.$modelValue, 2);
        });
      }
    };
  });


// REFS: 
// http://stackoverflow.com/questions/17344828/angularjs-should-i-use-a-filter-to-convert-integer-values-into-percentages
// http://stackoverflow.com/questions/13668440/how-to-make-a-percent-formatted-input-work-on-latest-angularjs
于 2014-10-30T02:54:10.230 回答
0

我修改了 abhaga 的答案以允许 .## 和 ## 输入。在我看来,这更加用户友好

link: function(scope, element, attr, ngModel) {
            ngModel.$parsers.unshift(
                function(viewValue){
                    var perc = parseFloat(viewValue);
                    if (perc<0 || perc>100 || !isFinite(perc)){
                        return null;
                    }
                    if (perc>1 && perc<=100){
                        return parseFloat($filter('number')(perc/100));
                    }
                    return perc;
                }
            );
            ngModel.$formatters.unshift(
                function(modelValue){
                    if(!isFinite(modelValue)){
                        return "";
                    }
                    return $filter('number')(parseFloat(modelValue)*100, 2);
                }
            );
        }
于 2015-04-27T17:55:49.063 回答