Search code examples
javascriptangularjsangular-translate

accessing stored locale from angular-translate FileStorage


I am using angular-translate with LocalStorage and it works very well. Locales are cached or stored on local disk. When the browser is closed and re-launched the chosen locale is persisted.

My question is how can I access that cached or stored locale that's on disk in one of my controllers? To better explain here's the workflow that is not working:

1. Launch browser to localhost and can see the site with previously chosen locale
2. Attempt to access the current locale from either the
    2.1 $translate.proposedLanguage()
    2.2 tmhDynamicLocale
3. Both are undefined -- even though the correct language is shown
4. Select language choice once more
5. current locale from both the above is now correct 

Here is the JSFiddle for the module and locale service. Not runnable code. Just an example of the code I'm using

I am trying to access currentLocale but it is undefined until the user makes a selection (again). I know it's stored somewhere since the original selection is persisted after browser exit.


Solution

  • After about 2 hours in a rabbit whole of API docs and angular-translate-* sources files I found that I can pass $translateLocalStorage to my controller and then call $translateLocalStorage.get() which will return that cached localId.

    That method pulls the localId from `$window.localStorage.getItem. That code is

    get: function (name) {
        if(!langKey) {
          langKey = $window.localStorage.getItem(name);
        }
    
        return langKey;
      }
    

    So all you would need to do is:

    angular.module('myModule')
      .controller('QueryController', function($scope, es, $translateLocalStorage) {
         $scope.show_results = function(results) {
            var currentLocale = $translateLocalStorgae.get();
     }
    });