NVO
NVO

Reputation: 2713

Can't use $translate.use in app.run: undefined

since I upgraded angular-translate from 2.9.0 to 2.15.2 I can't use the $translate.use() function anymore in my rootScope (app.run)

The value of $translate.use() is undefined, while loading the page. This is the code what I use to load the language and to change the language.

$rootScope.changeLanguage = function (langKey) {
    if(langKey.length == 2) {
        $translate.use(langKey.toLowerCase()+"_"+langKey.toUpperCase());
        $rootScope.language = langKey;
    } else if(langKey.length == 5) {
        $translate.use(langKey);
        $rootScope.language = langKey.substring(0,2);
    }
};

$rootScope.changeLanguage($translate.use());

This code gives me this error:

Uncaught TypeError: Cannot read property 'length' of undefined at m.e.changeLanguage (app.js:184)

(minified code, so $rootScope is renamed to m.e.)

This log line gives me the following:

console.log("trans", $translate.versionInfo(), $translate.use());

trans 2.15.2 undefined

How can I get this working again?

Upvotes: 1

Views: 526

Answers (1)

Vikasdeep Singh
Vikasdeep Singh

Reputation: 21766

You were getting this error because when script is running first time at that time langKey is undefined, so add check inside the changeLanguage function before using langKey like below. It will work:

    $rootScope.changeLanguage = function(langKey) {
      if (langKey) {
        if (langKey.length == 2) {
          $translate.use(langKey.toLowerCase() + "_" + langKey.toUpperCase());
          $rootScope.language = langKey;
        } else if (langKey.length == 5) {
          $translate.use(langKey);
          $rootScope.language = langKey.substring(0, 2);
        }
      }
    };

    $rootScope.changeLanguage($translate.use());

Upvotes: 1

Related Questions