Go AngularJs Multi-lingual use angular-translate

Source: Internet
Author: User
Tags i18n



This article transferred from: Http://www.tuicool.com/articles/zeymimB



With the increase in web traffic around the world, we are also constantly internationalizing and localizing applications as developers. When a user accesses our app, he should be able to switch locales immediately at runtime.



In view of the fact that we are developing a ANGULARJS client application, in particular we do not want users to have to refresh the page or access an entirely different URL. Of course, Angularjs can easily adjust the native language environment of those international readers, perhaps by creating different templates for different languages to serve the application.



However, this process can be cumbersome, what happens when we want to change the layout of the app? Each stand-alone template needs to be rebuilt and deployed. And the process should be very simple.



Say this "Angular-translate" today.



You can use Angular-translate to replace the way you create a new template, a ANGULARJS module that provides i18n (internationalization) services for your app. Angular-translate requires the creation of a JSON file that describes the translation data for each language. It then delays loading translation data for a specific language from the server only when necessary.



The Angular-translate library comes with a lot of built-in directives and filters, which makes our application internationalization easy. I



Let's study together.


  1. Installation: There are many ways to install, and you can use Nodejs if you use the Bower (front-end package manager), if you are not familiar with Google it can be used. The simplest of course is that you download it directly and bring it in. But you need to make sure that your library is placed behind Angularjs, and I don't want to say more:

    < script src= "path/to/angular.js" ></script>< Script src= "Path/to/angular-translate.js" > </SCRIPT>               

    The last point is, Angular-translate must be declared as a load dependency in your app:

    var app = Angular.module ( ' pascalprecht.translate ');   



  2. How to use: After installing angular-translate, declare it as an application dependency so that it can be used to translate the contents of the application. First, you need to provide translation data so that the application can really speak a new language. This step can be achieved by configuring the $translate service with the latest $translateprovider service. It's easy to use a new language for training applications. Simply use the config function on your app to provide different language translations for your app (such as English, German, Hebrew, and so on). First, you need to inject $translateprovider into the configuration function, just like this:


    Angular.module(‘angularTranslateApp‘, [‘pascalprecht.translate‘])
    .config(function($translateProvider) {
       //
       Translation will be here
    });
    


    To add a language, you must have $translateprovider find a translation table, which is a JSON object that contains the message (key) that will be translated into a specific value. Using a translation table allows us to write the translation data as a simple JSON file to be loaded remotely or set at compile time, such as:


    {  "name":"Hello AngularJs"} 


    In a translation table, a key (key) represents a translation ID, and its value represents a language-specific translation data. Now, add a translation table to your app first. $translateProvider provides a method called translations () to handle it.


    app.config(function($translateProvider) {
      $translateProvider.translations({
        "headline": "Hello there, This is my awesome app!",
        "intro": "And it has i18n support!"
      });
    });


    With this translation form, the app can use Angular-translate. Since this is a translation table added during configuration, the translation table can be accessed when the Angular-translate component is instantiated.



    Switch to the template section of the app first. To bind the key to the view is simple, just add the translation data to the view layer. With translate filters, you don't even have to touch a controller or service, or you don't have to worry about the view layer: Because you can decouple the translation logic from any controller or service, and you can make the view replaceable without touching the business logic code.



    Basically, the translate filter works like this:


    <h2>{{' headline ' | translate}}</h2><p>{{' intro_text ' | translate}}</ p>      


    It is now possible to translate the contents of the view layer, and also to avoid translating logic pollution controller logic; However, even if we do not use angular-translate, we can get exactly the same result, because only one language is involved in this sample application.



  3. Support for multiple languages at the same time: The above code case you already see a language setting, what if you have multiple languages at the same time? I may need to set up a scene that uses that language, which is no longer appropriate, and this plugin is also for us to provide such a function. Don't say much, just look at the code.


    app.config(function($translateProvider) {
      $translateProvider.translations(‘en‘, {
        HEADLINE: ‘Hello there, This is my awesome app!‘,
        INTRO_TEXT: ‘And it has i18n support!‘
      })
       .translations(‘de‘, {
        HEADLINE: ‘Hey, das ist meine großartige App!‘,
        INTRO_TEXT: ‘Und sie unterstzt mehrere Sprachen!‘
      });
    });


    OK, the above example is very concise, and multiple support is so simple. What if you want to set it up dynamically? When does this switch? Like the code above, I came in to show that? Is it English or German?



    To set the preferred language, you can use the $translateprovider.preferredlanguage () method. This method tells Angular-translate which of the registered languages is the language that the app should use by default. It requires a language key value to be used as the parameter, which points to a translation table. Now let's tell the app that it should use English as the default language:


    app.config(function($translateProvider) {
      $translateProvider.translations(‘en‘, {
        HEADLINE: ‘Hello there, This is my awesome app!‘,
        INTRO_TEXT: ‘And it has i18n support!‘
      })
      .translations(‘de‘, {
        HEADLINE: ‘Hey, das ist meine gro?artige App!‘,
        INTRO_TEXT: ‘Und sie unterstzt mehrere Sprachen!‘
      });
      $translateProvider.preferredLanguage(‘en‘);
    });


    OK, the above has solved the way we use the default in more than one language, then dynamically set it? What the hell? We continue to look down, to switch to a new language at runtime, you must use the Angular-translate $translate service. It has a use () method, which either returns a language key for the language currently being used, or passes a language key as a parameter, which allows angular-translate to use the language of the parameter.



    In order to feel how to use this function in real applications, we can add two translation IDs that represent translations, and the buttons added to the HTML template later use these two IDs: code snippets or the one above,


    app.config(function($translateProvider) {
      $translateProvider.translations(‘en‘, {
        HEADLINE: ‘Hello there, This is my awesome app!‘,
        INTRO_TEXT: ‘And it has i18n support!‘
      })
      .translations(‘de‘, {
        HEADLINE: ‘Hey, das ist meine gro?artige App!‘,
        INTRO_TEXT: ‘Und sie unterstzt mehrere Sprachen!‘
      });
      $translateProvider.preferredLanguage(‘en‘);
    });


    Next, we will implement a method on the controller to change the language at run time using the $translate service and its use () method. To do this, inject the $translate service into the application's controller, and then add a function to its $scope object:


    app.controller(‘TranslateController‘, function($translate, $scope) {
      $scope.changeLanguage = function(langKey) {
        $translate.use(langKey);
      }
    });


    Next, we reflect this change in the HTML template by adding a button for each language. You must also set a Ng-click directive on each button to invoke a function that changes the language at run time.


     
    
    <div ng-controller="TranslateController">
      <button ng-click="changeLanguage(‘de‘)" translate="BUTTON_TEXT_DE"></button>
      <button ng-click="changeLanguage(‘en‘)" translate="BUTTON_TEXT_EN"></button>
    </div>


    OK, this will solve the problem I have just thrown.


  4. Finally, the dynamic loading language angular $http service, we can dynamically load the language through the $translateprovider Registerloader method. First, you need to install the Angular-translate-loader-url extension to set up the Loader-url service, which requires a back-end server to return JSON data by handling the lang parameter. If you already have a back-end program that handles routing with the lang parameter, you can use it like this

    Bower Installing Loader-url Services:

    Bower Install Angular-translate-loader-url

    Likewise you don't want to install you go to github yourself the introduction of the download is also the same, the same needs to be introduced into the file under the Angularjs.

    OK, the specific use here is not much to say, you can search the plugin yourself to see the official documents here will not repeat the details.





Go AngularJs Multi-lingual use angular-translate


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.