2016-04-15 74 views
2

我正在嘗試建立一個基於this post的過濾器。我希望能夠通過切換選擇輸入來切換一種貨幣到另一種貨幣,但是我無法將輸入輸入到過濾器中。AngularJS - 帶外部輸出的貨幣兌換過濾器

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

提前感謝!

回答

1

不少新聞點擊這裏:

  • 首先,你的下拉列表位於在控制器外部
  • 你可以使用NG選項指令來清理你的選擇菜單
  • 你有NG - 單擊每個選項,這對於您試圖維護的複雜模型不起作用
  • 如果將整個選定選項傳遞給過濾器,則可以管理該範圍變量中保存數據的所有內容

這裏是一個工作示例 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; 
    } 
}); 
+0

古樸典雅。太感謝了! – Joe82

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因爲它不是很方便檢索與您存儲陣列的方式。