Joy Joy - 4 months ago 24
AngularJS Question

AngularJS i18n: define different fonts for different language

I am using Angular-i18n. My page is like:

<div translate="main.logged.message" translate-values="{username: '{{account.login}}'}">


I would like to use font-family
Lato
for English and
Microsoft Yahei
for Chinese.

I have tried:

:lang(zh) {
font-family: 'Microsoft Yahei';
}


But it is not working. And also checked the Doc: http://angular-translate.github.io/docs/#/guide. I cannot find the solution.

How to make it?




Update:

I found a post http://yukikodesign.com/orangutangy/?p=191, saying:


Specify English fonts first and then the Chinese fonts in your font list. This makes it so English fonts render with your desired fonts then the Chinese fonts pick up the other characters.


It's like:
font-family: "Lato", "Microsoft Yahei";


Surprisingly, it works! But it seems not a generic solution. Any better one?

Answer

You can add a variable 'lang' to the rootscope and then set this variable by read your cookie or localstorage or by read the browser setting (whatever way you go). Based on this variable you can add your language class='{{lang}}' to the same element like your ng-app attribute. Then you can change your font based on this class. If you provide to change the language dynamically by a function using $translate.use then change also your varaiable 'lang' on rootscope and write the changes back to your persistence layer like cookie or localstorage.

app.controller('Ctrl', ['$translate', '$scope', '$rootScope',
  function($translate, $scope, $rootScope) {

    //better set this in your run function based 
    //on your cookie or localstorage  
    $rootScope.lang = "en";  


    $scope.changeLanguage = function(langKey) {
      $translate.use(langKey);
      $rootScope.lang = langKey;
      //persist to cookie or localstorage here
    };
  }
]);

http://plnkr.co/edit/SnDjGceqNosrkwxflvh7?p=preview

Comments