gligoran
gligoran

Reputation: 3338

How to pass non-scope variables to AngularJS filter?

I have an array of pairs of amounts and currencies. The latter not just 'USD' or 'EUR', but is an object that contains formatting rules for that currency. I've written a filter for formatting the amount, but it only works if I hard code the formatting arguments:

// arguments: currency symbol, is symbol prefix, decimal symbol, digit group symbol
{{ entry.amount | currency24: '$',true,'.',',' } //USD example
{{ entry.amount | currency24: '€',false,'.',',' } //EUR example

What I'd like to be able to do is put the whole object in there like so:

{{entry.amount | currency24: entry.currency }} // currency object holds all the formatting parameters, but I could just as well pass them one by one

How can I achieve this?

EDIT: entry is not a part of $scope. It come from an ng-repeat:

ng-repeat="entry in entries"

That's why I'm having problems passing it to a filter.

Upvotes: 1

Views: 169

Answers (1)

halilb
halilb

Reputation: 4115

You are able to pass any object to filter just like you mentioned.

HTML markup stays the same you wanted:

<p ng-repeat="entry in entries">
  {{entry.amount | currency24: entry.currency }}
</p>

And the following code does what you asked for:

.controller('DemoController', function($scope) {
    $scope.entries = [{
      amount: 35,
      currency: {
        symbol: '$'
      }
    }, {
      amount: 40,
      currency: {
        symbol: '€'
      }
    }];
})

.filter('currency24', function() {
  return function(amount, currencyObject) {
    return amount + currencyObject.symbol;
  };
});

And check out this plunker.

Upvotes: 1

Related Questions