Michael
Michael

Reputation: 1079

How to use my own filter in ng-pluralize at count?

<ng-pluralize count="data.value | myFilter" when="{1: 'one item', 'othe': '{} items'}"> </ng-pluralize>

It is possible to use custom filter in count property? myFilter - need return integer value or float with 2 digits (2 not 2.00 or 2.10). Filter work like this:

app.filter('myFilter', function() {
  return function(input) {
    input = parseFloat(input);
    if (!Number.isInteger(input)) {
      return input.toFixed(2);
    }
    return input;
  }
}

I always got errors.

Syntax Error: Token '-' is an unexpected token at column 23 of the expression [this.value | myFilter-0] starting at [-0].

Upvotes: 1

Views: 74

Answers (1)

Anurag Srivastava
Anurag Srivastava

Reputation: 14423

You can set the filter inside the controller:

angular.module("myApp", [])
  .controller("myCtrl", function($scope, $filter) {
    $scope.data = {
      value: 1
    }

    $scope.data.filtered = $filter('myFilter')(2.1)
  })
  .filter('myFilter', function() {
    return function(input) {
      return parseFloat(input).toFixed(2);
    }
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <ng-pluralize count="data.value" when="{'1': 'one item', 'other': '{} items'}"> </ng-pluralize><br/>
  <ng-pluralize count="data.filtered" when="{'1': 'one item', 'other': '{} items'}"> </ng-pluralize>

  <pre>{{ data | json }}</pre>
</div>

Upvotes: 1

Related Questions