AngularJS 使用参数创建过滤器

示例

默认情况下,过滤器只有一个参数:对其应用变量。但是您可以将更多参数传递给函数:

angular
  .module('app', [])
  .controller('MyController', function($scope) {
    $scope.example = 0.098152;
  })
  .filter('percentage', function($filter) {
    return function (input, decimals) {
      return $filter('number')(input * 100, decimals) + ' %';
    };
  });

现在,您可以给percentage过滤器一个精度:

<span ng-controller="MyController">{{ example | percentage: 2 }}</span>
=> "9.81 %"

...但是其他参数是可选的,您仍然可以使用默认过滤器:

<span ng-controller="MyController">{{ example | percentage }}</span>
=> "9.8152 %"