Angular Translate is an AngularJS module called angular-translate which makes i18n and l10n easier with your Angular application. The acronym i18n stands for internationalization, and l10n for localization.
Why Angular Translate?
This library includes pluralization
as well as lazy loading
. The library also contains filters
and directives
. it is also very flexible in terms of building your own storages
, loaders
and error handlers
.
Sample App
Let’s build a sample app to try out angular-translate.
Create index.html
file and insert the code below.
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="UTF-8">
<title>Angular Translate Intro</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body ng-controller="ctrl">
<div class="dictionary">
<h1>{{'title' | translate}}</h1>
<p>{{'description' | translate}}</p>
<input type="button" ng-click="changeLang('en')" value="English">
<input type="button" ng-click="changeLang('zh-cn')" value="Chinese">
</div>
<script src="./js/angular.min.js"></script>
<script src="./js/angular-translate.min.js"></script>
<script src="./js/app.js"></script>
</body>
</html>
We are referencing angular.min.js
as well as angular-translate.min.js
libraries here. You can alternatively reference these libraries from teh CDN.
- AngularJS – https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular.min.js
- Angular Translate – https://cdnjs.cloudflare.com/ajax/libs/angular-translate/2.10.0/angular-translate.min.js
Now we need to create an app.js
file and insert the code below.
var app = angular.module('app', ['pascalprecht.translate']);
app.config(function($translateProvider) {
$translateProvider
.translations('en', {
"title": "Car",
"description": "A motor vehicle with four wheels;
usually propelled by an internal combustion engine."
})
.translations('zh-cn', {
"title": "汽车",
"description": "机动车与四个车轮;通常由内燃机驱动。"
});
$translateProvider.preferredLanguage('en');
});
app.controller('ctrl', [
'$scope', '$translate',
function($scope, $translate) {
$scope.changeLang = function changeLangFn(langKey) {
$translate.use(langKey);
};
}
]);
In the above code we inject the angular-translate module into our code. This way angular-translate gets to control our web pages.
Language Resource Files
Instead of definining translations inside our app.js
, we can define the files statically outside a different location.
$translateProvider.useStaticFilesLoader({
prefix: '/js/',
suffix: '/en.json'
});
The result will appear as the following. You can switch between languages by clicking the buttons.
Conclusion
Angular Translate is a great library for solving localization as well as internationalization and it’s very easy to add to your own Angular web sites.
The Github source for this article can be found in here.