Tips on storing chosen language in local storage or cookies using AngularJS

As a newcomer to angularjs, I am facing the challenge of saving the selected language from a dropdown menu in HTML to either local storage or cookies. This way, when a user navigates to another page, the language they previously chose will be loaded and used on the new page. Currently, whenever the page is changed or refreshed, the selected language disappears, requiring the user to select it again. I have utilized bower components for AngularJS and load translations from static files.

  1. This is my HTML code:

<div >
    <section class="caret">
      <h4>Select language for translation:</h4>
      <select class="caret" ng-change="translate()" ng-model="selectedLanguage">
        <option class="caret" value="en">English</option>
        <option class="caret" value="no">Norsk</option>
      </select>
    </section>
<div>

  1. My app

var app = angular.module('myApp', ['ngResource']);

  1. My controller

app.controller('myController',['$scope', 'translationService', 

function ($scope, translationService){  

  //Run translation if selected language changes
  $scope.translate = function(){
       translationService.getTranslation($scope, $scope.selectedLanguage);
   };
   
   //Init
   $scope.selectedLanguage = 'en';
   $scope.translate();
   
}]);

  1. My translation service

app.service('translationService', function($resource) {  

        this.getTranslation = function($scope, language) {
            var languageFilePath = 'translation_' + language + '.json';
            console.log(languageFilePath);
            $resource(languageFilePath).get(function (data) {
                $scope.translation = data;
            });


        };
});

Thank you.

Answer №1

If you only require String-Key-Value-Pairs, utilizing localStorage is a simple solution. It can be easily implemented as shown below.

However, when it comes to persisting Objects and similar data types, you may utilize JSON.stringify and JSON.parse for serialization purposes.

Below is the modified code with explanatory comments included: app.controller('myController',['$scope', 'translationService',

function ($scope, translationService){  

  $scope.translate = function(){
       translationService.getTranslation($scope, $scope.selectedLanguage);

       //Save changes to localStorage
       localStorage.setItem('selectedLanguage', $scope.selectedLanguage);
   };

   //Initialization
     //Set initial value or default
     $scope.selectedLanguage = localStorage.getItem('selectedLanguage') || 'en';
   $scope.translate();

}]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

SheetJS excel-cell customization

I'm using this example to export a worksheet from https://github.com/SheetJS/js-xlsx/issues/817. How can I apply cell styling such as background color, font size, and adjusting the width of cells to fit the data perfectly? I have looked through the do ...

Angular JS Unveiled: Deciphering HTML Entities

I'm looking for a solution to decode HTML entities in text using AngularJS. Here is the string I have: "&quot;12.10 On-Going Submission of &quot;&quot;Made Up&quot;&quot; Samples.&quot;" I need to find a way to decode this u ...

Learn how to dynamically insert an element into an angular scope using a click event

Currently, I am working on a function called onGroundUserClick within the Scope passedScope. The goal is to have a function triggered upon the completion of loading the iframe that will establish ng-click. var $tdName = $("<td/>", { ...

Button to save and unsave in IONIC 2

I am looking to implement a save and unsaved icon feature in my list. The idea is that when I click on the icon, it saves the item and changes the icon accordingly. If I click on it again, it should unsave the item and revert the icon back to its original ...

How to modify the content type in an Angular.js $http.delete request

When making a $http.delete request in my Angular app, I include a config object using the following approach: return $http.delete('projects/' + projectID + '/activityTypes', {data: [{id: 2}]}) This method attaches the values from my d ...

Unleashing the Potential: Integrating a Scanner Device with

Currently, I'm facing the challenge of integrating a Scanner device with my Angular application. On one of the pages dedicated to scanning, users are able to view an alert indicating the connection status of the Scanner as well as any scanned document ...

Tips on showing a response in an HTML node with Node.js and AngularJS

Just starting out with NodeJS and AngularJS. My goal is to fetch a response from an external site and display it in Angular JS. I managed to send the request and receive a response, but on the UI JSON appears as a string with forward slashes "\". For ...

Model updating with the addition of an item and triggering a secondary ng-repeat for refreshing

As I was working on the phone tutorial, I found myself pondering how to implement a specific use case. The browser renders a list of phones. When the user clicks on add phone for one of these phones, the function addItem is triggered and adds that phone ...

AngularJS Default Option Selection

I am encountering some difficulties with the preselection of a select-input in angularJS. The select-box is being populated by an array. <select class="form-control" ng-model="userCtrl.selected_country" ng-options="country.name for country in userCt ...

As I attempted to set up sb-admin-bs4-angular2-master, an application built with Node.js, I encountered an error message while running the npm install command

view image details here After running npm install -g ts-node, I proceeded with npm install only to encounter an error that left me clueless. Subsequently, when attempting npm start, a series of errors related to the gulp server or similar issues emerged. ...

Uncovered event listener in Angular tests

Imagine having a custom directive: angular.module('foo').directive('myDir', function () { return { restrict: 'E', link: function (scope) { var watcher = scope.$watch('foo, function () {}); scope.$on ...

How to utilize the ng-disable feature in AngularJS when using ng-repeat

In my current JavaScript code, I have two arrays of objects. The first array, named list1, consists of objects with keys "show" (boolean) and "number" (integer). The second array, named list2, only contains an integer key named "number". There is a button ...

AngularJS version 1.5.11 experiencing issues with ng-repeat functionality

Having an application built on angularJS v1.5.11, I encountered a major issue while attempting to use ng-repeat in a table format like below: <tbody> <tr ng-repeat="score in data.result"> <td ng-repeat="item in score"> {{ item }} & ...

Evaluating an AngularJS application using Selenium

Exploring the functionalities of an AngularJS application Discover more about Angular JS App Encountered an error while clicking on the UI Kit link on the website - Error at demoaj.Ajapp.main(Ajapp.java:16) Caused by: org.openqa.selenium.NoSuchEleme ...

Unable to display array retrieved from successful http get request on the webpage

I've been struggling to output the result from the success function in this specific way, but unfortunately, I haven't had any success. The code works fine when it comes to returning values for UpcomingEvents and displaying them in HTML, but when ...

What is the best way to eliminate index.html and exclamation mark from a URL when using AngularJs ui-router?

Recently, I've been working on my state configuration in JavaScript Currently, my URL appears as follows: https://i.stack.imgur.com/FEgjx.png I am looking to eliminate 'index.html' and the exclamation mark from my URL, similar to this exa ...

Issues with splicing an Angular array using pure JavaScript

Could someone please help me figure out what I'm doing incorrectly? I have some JSON data that I am converting into an array for use in an ng-repeat. Before looping through the array, I am checking the event dates against today's date and removin ...

Angular Translate - Utilizing translate-values attribute for translation

Having trouble using angular translate with dynamic translation values that need to be translated first. If you want a better explanation of the issue, check out this plunker: PLUNKER <p translate="PARAGRAPH" translate-values="{username: ('us ...

ng-repeat on a transcluded directive fails to show the properties of the object

Having trouble with menu directives. The bottom three menu items work fine, but the ones generated by an ng-repeat are missing attributes like route, icon, and label when I run the code. The ng-repeat seems to be creating the correct number of menu-items, ...

Transferring the $http.post request to a separate service function

Although I am new to AngularJS, I assure you that I am not stupid. I recently had a call in a controller that I wanted to move to a service in order to make it available to multiple controllers. $http.post("/admin/Leads/LoadLeads.ashx", dataObj) .succ ...