AngularJs pluralCat

857 Views Asked by At

I see that there's a pluralCat in each locale file

How to use it with angularJs ? I need translations for locales 'en','de','pl'

So I could use f.e. this

{{cardAmount | sth?}}

and depending on the value of cardAmount it would turn into one output of these

en: 0 cards , 1 card , 2 cards , ...  
de: 0 Karten , 1 Karte , 2 Karten , ...
pl: 0 kart , 1 karta , 2 karty , ... , 5 kart  

Where would I put my translations ? And where to put the code gluing pluralCat and my translations together

2

There are 2 best solutions below

0
On

As of version 1.3.3, $locale.pluralCat is an internal function - I would not rely on it. I'm sure angular will have more built in localization features in the future.

In the meantime I recommend using angular-translate. I'm using it (with one of its plugins - angular-translate-loader-url) to dynamically load my translations in JSON form (originally from a resx file).

I'm translating each noun in both singular and plural form (there are also other forms, like "few" in Polish and Russian...), and using logic like pluralCat, deciding in runtime if I should show the translation of Card_Singular or Card_Plural, etc...

0
On

Use ng-pluralize directive : https://docs.angularjs.org/api/ng/directive/ngPluralize

if you need it in your templates.

The directive will call $locale.pluralCat (of your current $locale) for you.

Otherwise, you can just inject $locale whenever you like and call directly $locale.pluralCat().

NB: $locale.pluralCat works fine in 1.2.x, 1.3.x and 1.4.x., unit tested with:

function pluralService($locale) {
    this.getPlural = function(count) {
        return $locale.pluralCat(count);
    };
}

angular.module('plurals', [])
    .service('plural', ['$locale', pluralService])
    ;



beforeEach(module('plurals'));

describe('plural', function() {

    beforeEach(inject(function($injector) {
        this.plural = $injector.get('plural');
    }));

    it('should return correct plural category', function() {
        expect(this.plural.getPlural(1)).toBe('one');
        expect(this.plural.getPlural(5)).toBe('other');
    });

});