获取Angular视图中的所有货币过滤器项

时间:2022-12-04 15:21:07

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.

我目前的工作逻辑应该根据用户选择的货币(dls,eur,brl)更改视图中的所有价格,我想知道是否有可能获得视图中的所有元素“货币“过滤器获取应用。例如

<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.

1 个解决方案

#1


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.

Angular允许您通过将一个名为filternameFilter的参数添加到控制器的构造函数中来传入过滤器。

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

这是一个显示以上内容的codepen:http://codepen.io/troylelandshields/pen/EKjwRy

#1


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.

Angular允许您通过将一个名为filternameFilter的参数添加到控制器的构造函数中来传入过滤器。

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

这是一个显示以上内容的codepen:http://codepen.io/troylelandshields/pen/EKjwRy