我正在尝试基于this post构建过滤器。我希望能够通过点击选项输入切换选择输入从一种货币切换到另一种货币,但我没有将输入输入过滤器。
我的HTML是:
<div ng-controller="myCtrl">
you have, {{money | currency}}...<br><br>
</div>
<select>
<option ng-click="currencySymbol = 'USD'; currencyRate=exchange.usd.rate">USD<option>
<option ng-click="currencySymbol = '£'; currencyRate=exchange.pound.rate">£<option>
<option ng-click="currencySymbol = '€'; currencyRate=exchange.euro.rate">€<option>
</select>
Angular部分:
angular
.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.money = 100;
$scope.exchange = [
{"usd":{"rate":1}},
{"pound":{"rate":0.702846}},
{"euro":{"rate":0.885055}}
];
})
.filter('currency', function() {
var defaultCurrency = 'USD';
return function(input, currencySymbol, currencyRate) {
var out = "";
currencySymbol = currencySymbol || defaultCurrency;
currencyRate = currencyRate || 1.00;
out = input * currencyRate;
return out + ' ' + currencySymbol;
}
});
您可以查看JsFiddle here
提前致谢!
答案 0 :(得分:1)
这里有一些更新:
这是一个工作示例 http://jsfiddle.net/r0m4n/dLLtzqyr/1/
这将是您简化的HTML:
<div ng-controller="myCtrl">
you have, {{money | currency: selectedCurrency}}...
<br>
<br>
<select ng-model="selectedCurrency" ng-options="item as item.label for item in exchange">
</select>
</div>
你的js:
angular
.module('myApp', [])
// controller here
.controller('myCtrl', function($scope) {
$scope.money = 100;
$scope.exchange = [{
label: "USD",
rate: 1
}, {
label: "£",
rate: 0.702846
}, {
label: "€",
rate: 0.885055
}];
$scope.selectedCurrency = $scope.exchange[0];
})
.filter('currency', function() {
return function(input, selectedCurrency) {
var out = "";
out = input * selectedCurrency.rate;
return out + ' ' + selectedCurrency.label;
}
});
答案 1 :(得分:0)
您可以使用过滤器货币定义3个参数。无论何时使用过滤器,都需要将这些参数提供给过滤器。在你的情况下:
<div ng-controller="myCtrl">
you have, {{money | currency:currencySymbol:exchange[2].euro.rate}}...<br><br>
</div>
在AngularJS世界中,您在|
之后调用过滤器,并使用:
作为参数的分隔符(第一个参数输入总是隐式给出)。
为了简化调试,您可以在过滤器中添加:
return function(input, currencySymbol, currencyRate) {
console.info('currency parameter', input, currencySymbol, currencyRate);
请注意,我对参数currencyRate进行了硬编码,因为使用存储阵列的方式检索它并不方便。