【问题标题】:AngularJS - Dynamically change currency symbol on a Filter?AngularJS - 动态更改过滤器上的货币符号?
【发布时间】:2016-06-12 21:41:58
【问题描述】:

问题背景:

我有一个下拉菜单,其中包含 4 个不同的国家/地区选项:UK(英国)、US(美国)、FR(法国)、GER(德国)。根据选择的下拉值,我需要在我的 Controllers Scope 对象上过滤价格以显示正确的货币符号,例如:

如果我在复选框中选择“FR”,我希望在过滤器上看到“€”符号:

如果我选择“UK”,我希望看到附加的“£”等等。

问题:

如上所述,我可以选择 4 个不同的国家,因此我需要能够动态更改货币过滤器。

我试图通过 Scope 上的模型属性来设置它,但到目前为止还没有成功。

守则:

目前我使用的是标准的AngularJSCurrency过滤器,如图:

       {{maxTextVal | currency : "€" : 2}}

maxTextVal 是控制器 Scope 对象上的值。在上面的代码中,我硬编码了欧元代码 (€) 来生成符号,我需要动态设置这个过滤器值。

是否可以在运行时更改此值?任何帮助将不胜感激。

【问题讨论】:

标签: angularjs angularjs-filter


【解决方案1】:

可以在运行时更改此设置,但我不确定货币过滤器是否有直接选项。

无论如何,您都可以编写一个使用$sce.trustAsHtml(value) 的自定义过滤器来正确显示符号。或者您也可以将带有currencyFilter 的过滤器注入您的作用域并调用该函数并在那里使用$sce

请看下面的演示或fiddle

angular.module('demoApp', [])
	.filter('currencyWithLocale', function(currencyFilter, $sce) {
    	return function(input, locale) {
        	locale = locale || {currency: '$'};
        	return $sce.trustAsHtml(currencyFilter(input, locale.currency));
        }
    })
	.controller('mainCtrl', MainCtrl);
    
function MainCtrl($sce) {
	var vm = this;
    angular.extend(vm, {
    	total: 10.1,
        locales: [{
        	id:0,
            short: 'GER',
            currency: '€'
        }, {
        	id:1,
            short: 'FR',
            currency: '€'
        },{
        	id:2,
            short: 'UK',
            currency: '£'
        }]
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainCtrl as ctrl">
    <select ng-model="ctrl.selectedLocale" ng-options="locale as locale.short for locale in ctrl.locales">
    </select>
    <span ng-bind-html="ctrl.total | currencyWithLocale: ctrl.selectedLocale"></span> 
    <!--<br/>
    below is not working because it's not $sanitized.<br/>
    {{ctrl.total | currency: ctrl.selectedLocale.currency}}-->

</div>

【讨论】:

  • 点击后我想要这样
【解决方案2】:

不是传递文字“€”,而是传递一个包含当前选定货币的范围变量:

{{maxTextVal | currency : selectedCurrency : 2}}

或者,假设您有一个选定的国家,并且该国家包含一种货币:

{{maxTextVal | currency : selectedCountry.currency : 2}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 2015-09-16
    • 2015-08-06
    • 1970-01-01
    相关资源
    最近更新 更多