AngularJS Create a filter with parameters


Example

By default, a filter has a single parameter: the variable it is applied on. But you can pass more parameter to the function:

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) + ' %';
    };
  });

Now, you can give a precision to the percentage filter:

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

... but other parameters are optional, you can still use the default filter:

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