M
M
Maxim2018-05-31 15:56:47
JavaScript
Maxim, 2018-05-31 15:56:47

How to add a class to a tag?

There is a template, when you click on languages, a class is added to them, but when you first load the page, you also need to add it to highlight the current language

<div ng-init="selectedLang = { currentLanguage } " class="buttonsPanelRow">
      <p id="ru" ng-class="{'setLanguageButtonActive':selectedLang === 'ru'}" class="setLanguageButton" ng-click='switchLanguage("ru"); selectedLang = "ru"'>Русский</p>
      <p id="en" ng-class="{'setLanguageButtonActive':selectedLang === 'en'}" class="setLanguageButton" ng-click='switchLanguage("en"); selectedLang = "en"'>English</p>
    </div>

In the controller
$scope.switchLanguage = function(key) {
      $translate.use(key);
      localStorage.setItem('NG_TRANSLATE_LANG_KEY', key);
    }

The current language is stored in localstorage, how can I highlight the selected language on first load?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philip Gaponenko, 2018-05-31
@maximkv25

onInitYou need to check the existence of the desired variable in the life cycle hook localStorageand, if such a variable exists, initialize it with selectedLangthe desired value.
If the variable localStoragedoes not exist, it should be initialized selectedLangwith a standard value, for example en.
https://angular.io/guide/lifecycle-hooks

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question