Live DemoAngularJS貨幣過濾器爲什麼用括號格式化負數?
爲什麼這樣的:
# Controller
$scope.price = -10;
# View
{{ price | currency }}
導致($10.00)
而非-$10.00
?
Live DemoAngularJS貨幣過濾器爲什麼用括號格式化負數?
爲什麼這樣的:
# Controller
$scope.price = -10;
# View
{{ price | currency }}
導致($10.00)
而非-$10.00
?
這是表示負面貨幣的流行方式。 Wikipedia:
在簿記中,欠款通常用紅色數字或括號中的數字表示,作爲表示負數的備選符號。
您可以在角源代碼中看到他們這樣做(negSuf
/negPre
):
function $LocaleProvider(){
this.$get = function() {
return {
id: 'en-us',
NUMBER_FORMATS: {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [
{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
},{ //Currency Pattern
minInt: 1,
minFrac: 2,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}
],
CURRENCY_SYM: '$'
},
是否有可用於覆蓋此行爲的可擴展性點? –
@ DMactheDestroyer你可以使用裝飾器,就像[我的回答](http://stackoverflow.com/a/30122327/1303135) – marc
@marc中所描述的,你是對的,謝謝!這比自定義過濾器更優雅。 –
你的意思是顯示 - $ 200元,而不是($ 10.00)?
默認情況下,至少angularJs版本1.2.1是用圓括號顯示。例如:($ 10.00))。
如果是這樣,這是我的情況。我創建了一個自定義過濾器:
var app = angular.module('myApp');
app.filter('customCurrency', ["$filter", function ($filter) {
return function(amount, currencySymbol){
var currency = $filter('currency');
if(amount.charAt(0) === "-"){
return currency(amount, currencySymbol).replace("(", "-").replace(")", "");
}
return currency(amount, currencySymbol);
};
}]);
所以將其委託給內置的貨幣過濾器和「裝飾」或「非裝飾」的括號。
我找不到方法來即時更改$ LocaleProvider。如果有人知道,請讓我知道。
歡呼 萊昂納多·科雷亞
如果您傳遞數字,此行將有助於:amount = amount +'';。它會將數字轉換爲字符串(不會改變實際的數字,否則charAt會導致數字上的錯誤) – Bowersbros
它通過檢查負數工作對我來說更好:
var app = angular.module('myApp');
app.filter('customCurrency', ["$filter", function ($filter) {
return function(amount, currencySymbol){
var currency = $filter('currency');
if(amount < 0){
return currency(amount, currencySymbol).replace("-", "(") + ')'
}
return currency(amount, currencySymbol);
};
}]);
我知道這是一個老問題,但接受的答案只回答爲什麼出現這種情況,沒有解決問題的具體辦法。我認爲,這樣做的「最正確的方式」,就是用像這樣一個裝飾:
angular
.module('app')
.config(['$provide', function($provide) {
$provide.decorator('$locale', ['$delegate', function($delegate) {
if($delegate.id == 'en-us') {
$delegate.NUMBER_FORMATS.PATTERNS[1].negPre = '-\u00A4';
$delegate.NUMBER_FORMATS.PATTERNS[1].negSuf = '';
}
return $delegate;
}]);
}]);
這只是調用一次,有效期爲依賴於它的任何過濾器,並且不需要自定義過濾您的貨幣格式。
如果你不介意保持括號,只想一個快速簡便的方法來實現這一
如:-($250.00)
嘗試以下操作:
<ul ng-repeat="data in customers">
<li>
Balance:
<span ng-if="data.balance<0">-</span>
<span ng-if="data.balance>0">+</span>
{{data.balance | currency}}
</li>
</ul>
如果你想刪除的()
,那麼你就可以創建您自己的過濾器或嘗試其他答案。
更新:Angular 1.4不再使用括號來表示負值,但現在使用「 - 」符號。這裏是一個討論的鏈接:https://github.com/angular/angular.js/issues/12870
我用marc描述的裝飾器返回.negPre和.negSuf來使用parens。
這是默認行爲。如果您想更改https://groups.google.com/forum/?hl=zh-CN#searchsearch/angular/goldshtein/angular/8mAc7h5NBd4/k6vo6B6HnIQJ – Chandermani