1

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.

Franco Aguilera
  • 617
  • 1
  • 8
  • 25
  • You should look into `$rootScope` to store your current currency. From which you can access in your filter. – Josue Alexander Ibarra Mar 02 '16 at 22:15
  • 1
    @JosueIbarra mmm... I don't think that's a good idea, have in mind that there are gonna be many values, so ... I don't think $rootScope it's a good approach – Franco Aguilera Mar 02 '16 at 22:17
  • I think you should possibly clarify exactly what the end result is that you want. Explain why you are wanting to get an array of the filtered prices, because while what you are asking might be possible there is almost definitely a better way to do it. – shieldstroy Mar 02 '16 at 22:18
  • 1
    I mean, keep the display logic of the currency in the filter. You only need one global variable with the current currency to change it in the whole application. – Josue Alexander Ibarra Mar 02 '16 at 22:20
  • @JosueIbarra oh! I see, maybe that could work, could you provide a minimal example ? – Franco Aguilera Mar 02 '16 at 22:26
  • Sure, im on mobile so i cant code right now. When i get back on my pc. – Josue Alexander Ibarra Mar 02 '16 at 22:34
  • The answer I added is similar to his suggestion. Instead of putting it on the $rootScope I am using a "value" service but using the $rootScope wouldn't be that much different. – shieldstroy Mar 02 '16 at 22:37

1 Answers1

2

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

shieldstroy
  • 1,307
  • 1
  • 10
  • 24