Internationalization module Angular-translate simple and convenient translation in English and other multi-language environment

Source: Internet
Author: User
Tags i18n

Many Web services face not only the local users, the multi-lingual environment can not only enhance the force lattice, more important is a user experience.

Angular.js as a solution to the front-end split, of course, can not be separated from the framework of the problem of internationalization, angular.js official out of a module angular-translate to solve the problem of multi-language internationalization.

We use the Bower Package management tool to manage dependencies, and click on the link to see how the Bower is used, which is no longer detailed.

Today's shared content directory:

    1. Pre-prep work with angular-translate modules

    2. Create filters to make HTML page content internationalized

    3. Create a service do the content internationalization in JavaScript scripts

    1. Pre-prep work with angular-translate modules

Download angular and angular-translate modules using the Bower management tool

Bower Install Angularbower install angular-translatebower install Angular-translate-loader-static-files
Then refer to it in the page <script src= "/vender/angular-1.3.8.js" ></script><script src= "/vender/ Bower-angular-translate-2.4.2/angular-translate.min.js "></script><script src="/bower_components/ Angular-translate-loader-static-files/angular-translate-loader-static-files.min.js "></script>

The first file angular-1.3.8.js not have to say more. You know.

The second file, Angular-translate.min.js, is an international module officially provided by angular.

The third file Angular-translate-loader-static-files.min.js module is the module that is used to read local files because our translations are independent JSON files.

We find a separate folder i18n is used to put JSON files, directories and files as follows hierarchy relationship:

/i18n/

En.json

Cn.json

The contents of the En.json file are as follows:

{"100001": "Login", "100002": "Register"}

The contents of the Cn.json file are as follows:

{"100001": "Login", "100002": "Register"}

The above 2 JSON files correspond to the same key, which we call a translation key. In different language files, the same translation key corresponds to the corresponding translation value. "Login" corresponding to "log in"

Next we need to inject dependency into:

var app = Angular.module (' myApp ', [' pascalprecht.translate ']). config ([' $translateProvider ', function ($ Translateprovider) {var lang = window.localstorage.lang| | ' CN '; $translateProvider. preferredlanguage (lang); $translateProvider. Usestaticfilesloader ({prefix: '/i18n/', suffix : '. JSON '});

Decomposition of the above code to see:

var app = Angular.module (' myApp ', [' pascalprecht.translate ']);

This sentence tells us that we have loaded the Angular-translate module with a dependency.

. config ([' $translateProvider ', function ($translateProvider)

The config function configures $translate service implementation with a $translateProvider service.

We used the Localstorage.lang to store the user's last selected language, if the user is the first time range, the default display Chinese (and loaded Cn.json file to translate)

$translateProvider. Preferredlanguage (Lang)

This sentence tells Angular.js which language is the default registered language.

$translateProvider. Usestaticfilesloader ({prefix: '/i18n/', suffix: '. json '});

The above statement tells us that Angular.js should load locally those internationalized language configuration files.

Prefix: Specifies the file prefix.

Suffix: Specifies the file suffix.

At this point you might think that only the prefix and suffix are the ones that should load that file. If there are dozens of languages in the i18n, do you want to load all the files?

It's not like that. It will be loaded in the default registered language. The default registration language is the following sentence.

var lang = window.localstorage.lang| | ' CN ';

If the user last visited the English station, window.localstorage.lang=en; Then for the/i18n/en.json file that will load

If the user first accesses the window.localstorage.lang=undefined, then by default we will load the/i18n/cn.json file

Then we decided to place a drop-down list box in the footer location for the selection language

<div> <select class= "language-switching" ng-controller= "Languageswitchingctrl" ng-model= "Cur_lang" ng-c Hange= "Switching (Cur_lang)" ><option value= "en" >english</option><option value= "cn" > Simplified Chinese </ Option> </select></div>

The language selector above is available in 2 languages, EN, cn

Ng-change function is triggered when we select an item change

The space also binds the model ng-model= "Cur_lang"

And then we look at what's inside the controller:

Angular.module (' myApp '). Controller (' Languageswitchingctrl ', [' $scope ', ' $translate ', function (scope, $translate) {        scope.switching = function (lang) {$translate. Use (lang);        Window.localStorage.lang = lang;    Window.location.reload ();    }; Scope.cur_lang = $translate. Use ();}]);

The switching method of the controller is executed when the Ng-change event is triggered. This method accepts the parameter value (EN or CN) that the drop-down list option passes over

Then execute the $translate. Use (lang) method. This method implements the ability to switch languages at run time.

What is the function of the Ng-model? The role here is that the page load drop-down list shows which language is currently used by default, or locates the select default.

All of our preparation environments are configured, and we'll start by introducing the application:

2. Create a filter to do the internationalization of HTML page content

Now we are ready to do in the HTML page internationalization, first think of a filter, the HTML page is the most convenient to use. Create T.js filter in the/filters/directory

Angular.module ("myApp"). Filter ("T", [' $translate ', function ($translate) {return function (key) {if (key) {return $ Translate.instant (key);}};});

Filter is very simple and convenient to use, to join us in a login page, login and register the link requires us to do internationalization.

<div ng-controller= "Loginctrl" > <div> <p> <a ui-sref= "App.login ({})" >{{' login ' | t:100001}}</a> <a ui-sref= "App.register ({})" >{{' register ' | T:100002}}</a> </p> </div></div>

This way, in different locales, Angular.js will load different language profiles, showing the translated values according to the translation ID.

3. We use internationalization in JavaScript scripts

Of course, some people say that it is possible to do it directly with filters, but individuals prefer to create a service that feels easy to use.

We created the T.js service in the/services/directory, which reads as follows:

Angular.module (' myApp '). Factory (' T ', [' $translate ', function ($translate) {var T = {t:function (key) {            if (key) {return $translate. Instant (key);        } return key; }}});

The service T returned a method T. Let's take a look at how internationalization is used in a controller.

If the login controller loginctrl.js has a login tag that needs to be internationalized:

Angular.module (' myApp '). Controller (' Lgoinctrl ', [' $scope ', ' t ', function ($scope, T) {$scope. login_title=t .        T (100001); }]);

First, you need to inject the T service dependency into the controller, and then call the T-Service's T method directly in the place where internationalization is required, and return the translated value by passing in the translation ID.

end*****

Internationalization module Angular-translate simple and convenient translation in English and other multi-language environment

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.