NVO
NVO

Reputation: 2713

function in rootscope, can't access rootscope variable

In my app.run I have an function which get some text from an global variable from an other file. In that variable there are some keywords with an language attribute, which allows me to only get the requested text and filter out the right language.

I made an function for that but I can't get access the $rootScope.language variable in that function which I need for getting the right text.

function getTourTranslation(key){
    console.log("getTourTranslation", key);
    var lang = $rootScope.language;
    var step = _.get(steps, key);
    return step[lang]
}

So language is undefined, and so $rootScope.language is, but the variable exists and contains the right language key for the current language on the site. How can I get the content of that variabele without passing the language as variable into the function?

I also tried as $rootScope.getTourTranslation = function(key) but no luck

edit:

This is how the language variable is filled. We use angular-translate, so that is the $translate service. This code is placed above the getTourTranslation function.

$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.$on('$translateChangeSuccess', function () {
    if($translate.use()){
        $rootScope.language = $translate.use().substring(0,2);
        if($state.$current && !$state.$current.self.abstract) {
            $state.reload();
        }
    }
});
$rootScope.changeLanguage($translate.use());

Upvotes: 0

Views: 155

Answers (2)

BotanMan
BotanMan

Reputation: 1417

It is not possible that variable defined on $rootScope is not available withing the same context.

I can imagine only one case: it calls getTourTranslation so early so none of changeLanguage or $translateChangeSuccess handler ran

Upvotes: 1

NVO
NVO

Reputation: 2713

The problem was, that $rootScope.language was called before it was initialized.

So, I placed the call to the getTourTranslation() function in an function which is called after firing an button. So, the right variables are now only initialized when they are needed instead of always.

So, I fixed two things, and that all based on the comment from @BotanMan

Upvotes: 0

Related Questions