Skip to content

Instantly share code, notes, and snippets.

@adrai
Last active August 27, 2018 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrai/54e3d4b2356dfd6934b4842f7c7b4dfc to your computer and use it in GitHub Desktop.
Save adrai/54e3d4b2356dfd6934b4842f7c7b4dfc to your computer and use it in GitHub Desktop.
ng-i18next
if (window.i18next) {
window.i18next
.use(window.i18nextXHRBackend)
.use(window.i18nextBrowserLanguageDetector)
.init({
debug: false,
fallbackLng: 'en',
backend: {
loadPath: '../locales/{{lng}}/{{ns}}.json'
},
ns: ['translations'],
defaultNS: 'translations'
}, function (err, t) {
console.log('resources loaded');
}
);
}
angular.module('MyApp', ['jm.i18next']).controller('MyDirectiveCtrl', function ($rootScope, $scope, $timeout, $i18next, $filter) {
'use strict';
$scope.i18nextReady = false;
$scope.$on('i18nextLanguageChange', function () {
console.log('Language has changed!');
if (!$scope.i18nextReady) {
$timeout(function () {
$scope.i18nextReady = true;
}, 500);
}
});
$scope.changeLng = function (lng) {
$i18next.changeLanguage(lng);
};
});
<!doctype html>
<html ng-app="MyApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<title>Angular.js App</title>
<script src="https://code.angularjs.org/1.7.3/angular.min.js"></script>
<script src="https://code.angularjs.org/1.7.3/angular-sanitize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/i18next/11.6.0/i18next.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/i18next-xhr-backend/1.5.1/i18nextXHRBackend.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/i18next-browser-languagedetector/2.2.3/i18nextBrowserLanguageDetector.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-i18next/1.0.4/ng-i18next.min.js" ></script>
<script src="directive.js"></script>
</head>
<body>
<div ng-controller="MyDirectiveCtrl">
<div id="root">
<div class="App">
<div class="App-header">
<img src="https://blobscdn.gitbook.com/v0/b/gitbook-28427.appspot.com/o/spaces%2F-L9iS6Wm2hynS5H9Gj7j%2Favatar.png?generation=1523462254548780&alt=media" class="App-logo" alt="logo">
<h2 ng-i18next="[i18next]({ 'tech': 'angular', 'lib': 'ng-i18next' })title">Welcome to angular using ng-i18next</h2>
</div>
<button ng-click="changeLng('de')">de</button>
<button ng-click="changeLng('en')">en</button>
<div class="App-intro" ng-i18next="description">Switch language between english and german using buttons above.</div>
</div>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment