Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist selected language in LocalStorage while using Angular-translate?

I am new to angular-translate in my Angular app.

Requirement :

I have to create a multi language application in AngularJS where user has an option to set his language. So, for that I have to load translations from files and save that preferred language in localStorage. So that if the user comes again to access the application he will be displayed the previously set language.

What i have done so far :

Loaded translations from files by using $translateProvider.useStaticFilesLoader

Code :

var app = angular.module("myLangApp", ['pascalprecht.translate'])
app.config(function($translateProvider) {
$translateProvider.useStaticFilesLoader({
        prefix: 'languages/',
        suffix: '.json'
      });
    $translateProvider.useLocalStorage();
});

Application works fine if I comment this line:

// $translateProvider.useLocalStorage();

But if I use it, I am getting this error on the console:

Console error for the above code.

I have also included the angular-translate-storage-local.min.js file in my index.html.But no success.

I have also seen these questions in SO, but they don't help: Angular-translate's localStorage: Unknown provider: $translateLocalStorageProvider

Any immediate help will be highly appreciable. Thanks

like image 339
Creative Learner Avatar asked Oct 06 '15 06:10

Creative Learner


1 Answers

Here's the documentation on storage with angular translate

What you'll soon realize after reading it is that the angular-translate-storage-local library is meant to be used together with the angular-translate-storage-cookie library. Since local storage is not supported on some of the older browsers (example : IE 7 or below), angular translate want to have a fall back option to use cookies when local storage won't do the trick.

The error is caused by angular-translate-storage-local trying to inject its fall back option angular-translate-storage-cookie.

To circumvent this problem, you'll want to install angular-translate-local-cookie.

Beware that angular-translate-local-cookie tries to inject ngCookie which is a library that you'll have to install as well as set the dependency injection for your app. Injection should be

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

Also, the wrong ordering of the include files in your index.html can also cause problems for you. The proper order should be

<script type="text/javascript" src="vendor/angular-cookies/angular-cookies.min.js"></script>
<script type="text/javascript" src="vendor/angular-translate-storage-cookie/angular-translate-storage-cookie.min.js"></script>
<script type="text/javascript" src="vendor/angular-translate-storage-local/angular-translate-storage-local.min.js"></script>
like image 57
Jun Duan Avatar answered Sep 17 '22 21:09

Jun Duan