AngularJS Custom filters Create a filter with parameters

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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 %"


Got any AngularJS Question?