AngularJS - Internationalization

Привет,野心勃勃的网页开发者们!今天,我们将踏上一段激动人心的旅程,探索AngularJS国际化的世界。作为你友好的邻居计算机科学老师,我在这里引导你了解这个迷人的主题。所以,拿起你最喜欢的饮料,舒服地坐下来,让我们一起深入探讨!

AngularJS - Internationalization

Что такое internationalization?

Прежде чем мы начнем программировать, поймем, что означает internationalization. Представьте, что вы создали потрясающий веб-сайт, но только на английском языке. Что, если вы хотите, чтобы люди из разных стран имели к нему доступ? Вот где на помощь приходит internationalization! Это как дать вашему веб-сайту паспорт для путешеcтвия по всему миру.

Internationalization (часто сокращается как i18n - между 'i' и 'n' 18 букв) - это процесс designing вашего приложения так, чтобы его можно было адаптировать для различных языков и регионов без engineering изменений.

Why is Internationalization Important?

Подумайте об этом так: если бы у вас была冰淇淋店, вы бы предлагали только один вкус? Конечно нет! Вы бы хотели удовлетворить разные вкусы. То же самое и с веб-сайтами. Internationalizing ваше приложение AngularJS делает его доступным и удобным для пользователей по всему миру. Это как предлагать цифровой мороженое всех вкусов!

Теперь, переберем руки и посмотрим, как AngularJS делает internationalization breeze.

Setting Up AngularJS for Internationalization

First things first, we need to set up our AngularJS application to handle internationalization. We'll be using the angular-translate library, which is like a magic wand for translating our app.

Here's how we set it up:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-translate/2.18.4/angular-translate.min.js"></script>
</head>
<body>
<div ng-controller="TranslateController">
<!-- Our app content will go here -->
</div>
<script src="app.js"></script>
</body>
</html>

In our app.js file, we'll set up our AngularJS module and configure the translate provider:

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

app.config(['$translateProvider', function ($translateProvider) {
// Configuration will go here
}]);

app.controller('TranslateController', function($scope, $translate) {
// Controller logic will go here
});

Example Using Danish Locale

Now, let's create a simple example where we'll translate our app into Danish. Why Danish, you ask? Well, why not! Plus, I once had a student who was obsessed with Danish pastries, so this one's for you, Lars!

Let's update our app.js:

app.config(['$translateProvider', function ($translateProvider) {
$translateProvider.translations('en', {
TITLE: 'Hello',
FOO: 'This is a paragraph.',
BUTTON_LANG_EN: 'English',
BUTTON_LANG_DA: 'Danish'
});
$translateProvider.translations('da', {
TITLE: 'Hej',
FOO: 'Dette er et afsnit.',
BUTTON_LANG_EN: 'Engelsk',
BUTTON_LANG_DA: 'Dansk'
});
$translateProvider.preferredLanguage('en');
}]);

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

Here's what's happening:

  1. We define translations for English ('en') and Danish ('da').
  2. We set English as the preferred language.
  3. We create a changeLanguage function in our controller to switch languages.

Now, let's update our HTML:

<div ng-controller="TranslateController">
<h2>{{ 'TITLE' | translate }}</h2>
<p>{{ 'FOO' | translate }}</p>
<button ng-click="changeLanguage('en')">{{ 'BUTTON_LANG_EN' | translate }}</button>
<button ng-click="changeLanguage('da')">{{ 'BUTTON_LANG_DA' | translate }}</button>
</div>

Output

When you run this code, you'll see:

  • A title saying "Hello"
  • A paragraph saying "This is a paragraph."
  • Two buttons labeled "English" and "Danish"

Click the "Danish" button, and voila! Your app now speaks Danish:

  • The title changes to "Hej"
  • The paragraph says "Dette er et afsnit."
  • The buttons are now labeled "Engelsk" and "Dansk"

It's like magic, isn't it? But remember, it's not magic - it's the power of AngularJS and your coding skills!

Example Using Browser Locale

Now, let's take it up a notch. What if we want our app to automatically use the user's browser language? It's like having a website that speaks your language before you even ask!

Let's modify our app.js:

app.config(['$translateProvider', function ($translateProvider) {
$translateProvider.translations('en', {
TITLE: 'Hello',
FOO: 'This is a paragraph.',
BUTTON_LANG_EN: 'English',
BUTTON_LANG_DA: 'Danish'
});
$translateProvider.translations('da', {
TITLE: 'Hej',
FOO: 'Dette er et afsnit.',
BUTTON_LANG_EN: 'Engelsk',
BUTTON_LANG_DA: 'Dansk'
});
$translateProvider.useLocalStorage();
$translateProvider.fallbackLanguage('en');
$translateProvider.registerAvailableLanguageKeys(['en', 'da'], {
'en*': 'en',
'da*': 'da'
});
$translateProvider.determinePreferredLanguage();
}]);

What's new here?

  1. We use local storage to remember the user's language preference.
  2. We set English as the fallback language.
  3. We register available language keys.
  4. We use determinePreferredLanguage() to automatically detect the browser's language.

Output

Now, when a user visits your website:

  • If their browser language is set to Danish, they'll see the Danish version.
  • If it's set to any other language, they'll see the English version (our fallback).
  • The chosen language will be remembered for their next visit.

It's like your website is a chameleon, adapting to each user's environment!

Conclusion

And there you have it, folks! We've turned our AngularJS application into a multilingual marvel. Remember, internationalization is not just about translation - it's about creating a welcoming experience for users around the world.

As you continue your coding journey, always keep your users in mind. Whether they're in Copenhagen or California, your app can now greet them in a language they understand.

Keep practicing, stay curious, and who knows? Maybe one day you'll create an app that speaks more languages than C-3PO! Until next time, happy coding!

Method Description
$translateProvider.translations(langKey, translationTable) Adds a new translation table for a specific language
$translateProvider.preferredLanguage(langKey) Sets the preferred language
$translateProvider.useLocalStorage() Uses local storage to remember language preference
$translateProvider.fallbackLanguage(langKey) Sets a fallback language
$translateProvider.registerAvailableLanguageKeys(keys, aliases) Registers available languages and their aliases
$translateProvider.determinePreferredLanguage() Automatically detects the browser's preferred language
$translate.use(langKey) Changes the current language

Credits: Image by storyset