2013-12-11 6 views
12

숫자를 형식화하고 각도로 복수화하고 싶습니다. 나는 무엇을 시도했다angularjs에서 숫자를 복수화하고 형식을 지정하는 방법

  0 => "John has no bitcoins" 
     1 => "John has 1 bitcoin" 
     2 => "John has 2 bitcoins" 
12345.6789 => "John has 12,345.67 bitcoins" 

:

(bitcoins의 번호 부여) 예를 들어

John has 
<ng-pluralize count="bitcoin_amount | round:2" 
       when="{'0': 'no bitcoins', 
        '1': '1 bitcoin', 
        'other': '{} bitcoins'}"> 
</ng-pluralize> 

하지만이 때문에 숫자와 동일 또는 1000보다 더 들어 비참하게 실패, 그들이있다 count 특성에 1,000으로 전달되므로 수천 개만 표시됩니다. 예 : 예는 this demo의 상자 number of people1,000을 붙여

1001 => 1 
1000 => 1 
2000 => 2 
etc... 

보십시오.


어떻게 번호를 배열하고 복수로 복수화 할 수 있습니까?

답변

23

여기서 정규 표현을 사용할 필요가 없습니다.

당신은 너무처럼 ng-pluralize 지침의 when 속성에 직접 로직을 전달할 수 있습니다

<ng-pluralize count="amount" when="{'0': 'no bitcoins', 
        '1': '1 bitcoin', 
        'other': '{{amount | number:2}} bitcoins'}"> 
</ng-pluralize> 

Working plunker합니다.

5

쉼표 만 제거하고 처리하도록 할 수 있습니까?

John has 
<ng-pluralize count="bitcoin_amount.replace(',','') | round:2" 
       when="{'0': 'no bitcoins', 
        '1': '1 bitcoin', 
        'other': '{} bitcoins'}"> 
</ng-pluralize> 

jsfiddlehttp://jsfiddle.net/9zmVW/

1

당신이 원하는 경우 's'를 추가로 기본 설정 할 수있는 일반적인 방법,

와 문자열로 특정 복수형을 통과 :

function plural(s, pl){ 
    var n= parseFloat(s); 
    if(isNaN(n) || Math.abs(n)=== 1) return s; 
    if(!pl) return s+'s'; 
    return s.replace(/\S+(\s*)$/, pl+'$1'); 
} 

// test: 
[0, .5, 1, 1.5, 2].map(function(itm){ 
    return [plural(itm+' bitcoin'), 
    plural(itm+' box', 'boxes'), 
    plural(itm+' foot', 'feet')]; 
}).join('\n'); 


// returned values: 
0 bitcoins, 0 boxes, 0 feet 
0.5 bitcoins, 0.5 boxes, 0.5 feet 
1 bitcoin, 1 box, 1 foot 
1.5 bitcoins, 1.5 boxes, 1.5 feet 
2 bitcoins, 2 boxes, 2 feet 
1

l10nsngPluralize을 사용하고 싶지 않고 로직을 현지화 스토리지에 저장하려는 경우 사용할 수 있습니다. L10ns은 복수화 처리를위한 사실상의 표준이되는 ICU의 Messageformat을 사용합니다. ICU의 Messageformat은 CLDR를 사용합니다. CLDR은 Apple이나 Google과 같은 많은 주요 업체에서 사용하고 사용하는 데이터 저장소입니다.

정상적인 영어로는 두 개의 복수형 인 singularplural이 있습니다. CLDR은 6 가지 종류의 복수형을 정의합니다. 그리고 그들은 zero, one, two, few, manyother입니다. Onetwo은 반드시 1과 2를 의미하지 않습니다.

예를 들어 CLDR에서 English에 대해 두 개의 복수형을 정의합니다. Oneother. l10ns에 번역 인터페이스를 사용하면 각 복수형의 예가 표시됩니다.당신이 L10ns를 사용하는 경우

그래서 당신의 예는 다음과 같습니다 위에서

{bitcoins, plural, =0{no bitcoins} one{1 bitcoin} other{# bitcoins}}. 

, =0은 정확한 사건을 목표로하고있다.

자세한 내용은 documentation을 확인하십시오.