Search code examples
javascriptangularjsfiltercurrency

get all currency filter items in an Angular view


I'm currently working in a logic that should change all prices in a view according to the user selected currency (dls, eur, brl), I was wondering about if it is possible to get all the elements in a view in where the "currency" filter get's applied. e.g.

<div>
    {{ somePrice | currency }}
    {{ anotherPrice | currency }}
    {{ vacationTicketCost | currency }}
</div>

and in the controller do some magic that ends up with an array like

var pricesArray = [somePrice, anotherPrice, vacationTicketCost];

so that in that way I would be able to apply the currency change to all the values. Is that possible or should I look for another approach ?

Regards.


Solution

  • What your asking is probably not a great idea because it requires your controller to know about your view. Instead what you want to do is pass the currency filter into your controller and use it from there to create your display values. Then you can have them in your controller as well.

    angular.module("app", [])
        .value("currentCurrency", "eur")
        .controller("controller", function(currentCurrency, currencyFilter){
            var vm = this;
            vm.val = "1.25";
            vm.currentCurrency = currentCurrency;
    
            vm.displayValue = currencyFilter(vm.val, vm.currentCurrency);
        });
    

    Angular allows you to pass in filters by adding a parameter called filternameFilter into the constructor function of your controller.

    Here is a codepen showing the above: http://codepen.io/troylelandshields/pen/EKjwRy