AngularJS translation module
A work in progress module for AngularJS to implement i18n in your apps!
After publishing this module, it turned out that there are a few other i18n and l10n modules out there, which all follow a different approach. So you might find these also interesting:
- (angularjs-localizationservice by @lavinjj)[https://github.com/lavinjj/angularjs-localizationservice]
- (angular-l10n by @4vanger)[https://github.com/4vanger/angular-l10n]
- (ng-translate by @StephanHoyer)[https://github.com/stephanhoyer/ng-translate]
Please install these things:
Then just clone the repository, navigate into the project and run
npm install
bower install
This will install all dependencies that are needed to make a build:
grunt build
grunt build will lint your the code, run unit tests, concat
files and generate the following:
dist/angular-translate-x.x.x.js
dist/angular-translate-x.x.x.min.js
Embed one of these files in your project.
First you have to inject the ngTranslate module as a dependency into your app:
var app = angular.module('myApp', ['ngTranslate']);
After that configure the $translateProvider and set up a translation table:
(if you know a better way to handle this, please lemme know)
app.config(['$translateProvider', function ($translateProvider) {
$translateProvider.translations({
'TITLE': 'Hello',
'FOO': 'This is a paragraph',
'COPYRIGHT_TEXT': '© {{value}}'
});
}]);
Great, the translation service now know your translation table. Now use the provided translateFilter
to translate your translation ID's in the view:
...
<body>
<h1>{{ 'TITLE' | translate }}</h1>
<p>{{ 'FOO' | translate }}</p>
</body>
When taking a look at COPYRIGHT_TEXT you might notice the {{name}}. This, of course, is a
string interpolation just like you already use it when developing angular apps.
You can assign the value of a specific identifier within a translation ID via string expression:
...
<footer>
<p>{{ 'COPYRIGHT_TEXT' | translate:'{"value": "foo"}' }}</p>
</footer>
The passed string gets parsed by $parse in translateFilter and then interpolated by $interpolate in $translate.
However, in some cases you don't know the value you wanna pass into a translation ID. In that case, you have to assign the values to an object model on the scope to pass it through the filter.
Controller:
app.controller('ctrl', function ($scope) {
$scope.translationData = {
value: 3
};
});
View:
<div ng-controller="ctrl">
<footer>
<p>{{ 'COPYRIGHT_TEXT' | translate:translationData }}</p>
</footer>
</div>
This is currently the only way to deal with dynamic translations, since AngularJS doesn't provide the functionality to pass named parameters through filters. (I opened a PR here, please help to push this forward)
That's it! Feel free to help out, making this thing better!
Cheers