Set the local storage value to the $scope variable

I am attempting to set a local storage value to a $scope variable and utilize that $scope variable in ng-model to populate dropdowns. However, the code I have tried is not functioning as expected.

You can view the Plunker example here: https://plnkr.co/edit/Ile7ehzxB9PcoeTKk1B6?p=preview

It is crucial for me to initialize it from local storage only, since the data is exclusively received through local storage.

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script>
    var app = angular.module('appNew', []);
    app.controller('controllerNew', function($scope) {
      $scope.dataSet = ["A", "B", "C"];
      localStorage['color'] = {"A":"Red","B":"Red","C":"Blue"};
      var colorVar = localStorage['color'] || '';
      $scope.selectColor = colorVar;
    });
  </script>
</head>

<body ng-app="appNew">
  <table class="table TableOne" ng-controller="controllerNew">
    <thead>
      <tr>
        <th>Serial</th>
        <th>Data</th>
        <th>Dropdown</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="data in dataSet">
        <td>{{$index + 1}}</td>
        <td>{{data}}</td>
        <td>
          <select ng-model="$parent.selectColor[data]">
            <option value="">-- Select --</option>
            <option value="Red">Red</option>
            <option value="Blue">Blue</option>
            <option value="Green">Green</option>
          </select>
        </td>
      </tr>
    </tbody>
  </table>
</body>

</html>

Answer №1

LocalStorage is a method that allows the storage of key/value pairs at present - you can read more about it in the documentation provided:

The Web Storage API offers ways for browsers to store key/value pairs, which is much simpler than using cookies.

To store an object, you can use `stringify`, and to retrieve it from LocalStorage, you can use `parse` like this:

localStorage['color'] = JSON.stringify({"A": "Red","B": "Red","C": "Blue"});
$scope.selectColor = JSON.parse(localStorage['color']);

For a working example, refer to the code snippet below - note that some snippets may not work due to restrictions - so take a look at the plnkr code here.

var app = angular.module('appNew', []);
app.controller('controllerNew', function($scope) {
  $scope.dataSet = ["A", "B", "C"];
  
  localStorage['color'] = JSON.stringify({"A": "Red","B": "Red","C": "Blue"});
  $scope.selectColor = JSON.parse(localStorage['color']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body ng-app="appNew">
  <table class="table TableOne" ng-controller="controllerNew">
    <thead>
      <tr>
        <th>Serial</th>
        <th>Data</th>
        <th>Dropdown</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="data in dataSet">
        <td>{{$index + 1}}</td>
        <td>{{data}}</td>
        <td>
          <select ng-model="selectColor[data]">
            <option value="">-- Select --</option>
            <option value="Red">Red</option>
            <option value="Blue">Blue</option>
            <option value="Green">Green</option>
          </select>
        </td>
      </tr>
    </tbody>
  </table>
</body>

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

Is there a counterpart to ES6 "Sets" in TypeScript?

I am looking to extract all the distinct properties from an array of objects. This can be done efficiently in ES6 using the spread operator along with the Set object, as shown below: var arr = [ {foo:1, bar:2}, {foo:2, bar:3}, {foo:3, bar:3} ] const un ...

Refresh the data displayed in the ng-repeat loop

I need to update the "frais" of all values displayed by ng-repeat in my code. I am working with angularJS and PHP. Can someone please guide me on how to do this? file.html <ion-content class="padding" ng-controller="FactureAdminCtrl"> <ion-list ...

What is the best way to implement multilanguage support in nodejs without relying on cookies or external modules?

Currently, I am in the process of transitioning all my projects to node.js in order to enhance my JavaScript skills. Using Node.js along with the Express module, one of my clients who runs a translation company has requested that I incorporate two language ...

Unable to retrieve req.files using multer from the req object

I have been attempting to send a file to the server using a NodeJs script. Below are the steps I am taking. HTML <md-tab label="Upload log"> <md-content class="md-padding" id="popupContainer" ng-cloak> <h4>Send a zip file< ...

Angular 13 does not currently have support for the experimental syntax 'importMeta' activated

Since upgrading to angular 13, I've encountered an issue while attempting to create a worker in the following manner: new Worker(new URL('../path/to/worker', import.meta.url), {type: 'module'}) This code works as expected with "ng ...

Retrieve the date from the event

Incorporating fullcalendar v2.0.2, I am currently developing a copy/paste system for events. By right-clicking, I am able to copy the event with the help of a small menu. Upon right-clicking on the calendar during a week view, I am tasked with calculating ...

Unusual shift in the modal's behavior occurs when the parent component's style.transform is applied

I have encountered an unusual issue with a modal's appearance and functionality. The modal is designed to enlarge images sent in a chat, with the chat upload preview div serving as the parent element and the modal as the child element. This strange be ...

Guide on utilizing AngularJS Filter service without HTML for Chrome extension development

Currently, I am attempting to utilize the filter service in AngularJS within my Chrome extension. However, I am unsure of how to properly obtain and inject it into my function. At this time, my code looks like: chrome.contextMenus.onClicked.addListener(fu ...

Tips for optimizing Angular source code to render HTML for better SEO performance

Our web platform utilizes Angular JS for the front-end and node js for the backend, creating dynamic pages. When inspecting the code by viewing the source, it appears like this: For our business to succeed, our website needs to be SEO-friendly in order to ...

How can I extract specific data from a JSON response and populate a select dropdown with AngularJS?

My current project involves making an http.get request to fetch a list of airports. The JSON response is packed with information, presenting a series of objects in the format shown below {"id":"1","name":"Goroka","city":"Goroka","country":"Papua New Guine ...

Stop objects from shifting while easily applying a border

I have a code that adds a red border around elements when you mouseover them and removes it when you mouseout. However, the elements jump around when the border is added because it changes their dimensions. Is there a way to stop this jumping behavior? ...

Formik: encountering target as undefined while passing Material UI Date Picker as prop to React Component

I'm currently working on developing a component that can be reused. The idea is to pass form fields as props, but I ran into an issue when clicking on the datepicker field. The error message that pops up is: TypeError: target is undefined Any sugge ...

Utilizing MEAN.js for uploading images

Following a tutorial on the MEAN stack, I am looking to implement an image upload feature using MongoDB on a server. Resources: Angular directive for file uploads create-spot.client.view.html <div data-ng-controller="SpotsCreateController"> &l ...

developing authentication codes using javascript

Currently, I am working on developing a sign-up system that allows users to easily generate a random string with the click of a button. The generated string can then be shared with non-users who wish to sign up. The new user will need to enter their chose ...

The syntax of AngularJS directives

Apologies for my lack of experience with this question :) I am working on displaying a progress bar in AngularJS using UI Bootstrap. The directive works perfectly when the value is hardcoded: <progress percent="67"></progress> However, I en ...

Angular 2: Enhancing User Experience with Pop-up Dialogs

Looking to implement a popup dialog that requests user input and returns the value. The popup component is included in the root component, positioned above the app's router outlet. Within the popup component, there is an open() method that toggles a ...

Issue with h2 tag within JQuery's read more feature

How can I modify my jQuery code to wrap the middle text in an h2 tag? I am currently using a code snippet from code-tricks. You can find the original code snippets here: $(document).ready(function() { var showChar = 100; var ellipsestext = "..."; ...

The function body.getReader() doesn't seem to be functioning properly on Ubuntu

I am currently in the process of deploying a project on Ubuntu Server 22.04. The tech stack I am using is Next.js + Nest.js. I have come across an issue where my Fetch API behaves differently - on my localhost (macOS) everything works smoothly and I rece ...

Is there a way to transform an HTMLCollection into an array without depleting it of its elements?

I've been attempting to transform a collection of 4 divs in HTML into an array, but all my efforts seem to lead to the array becoming void. <div class="container"> <div class="shape" id="one"></div> <div class="sh ...

Why was the 'Symbol' type introduced in ECMA-262-v6 and what purpose does it serve?

Can you explain the purpose of the 'Symbol' type in ECMA-262-v6? Is it used for fast path implementation for object keys? How does it work internally - does it hash with the assurance that the underlying data remains unchanged? ...