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

I'm looking to automate a system response whenever a user inputs something - how can I achieve this using NodeJS and Socket

I'm looking to create a feature where, if a user enters a specific command, the socket.io will respond with a predefined message. For example: Input: !hi Output: hello! If anyone knows how to achieve this, I'd appreciate some guidance, tha ...

Steps for implementing success handler in Angular $resource requests1. Define a function that

I'm feeling a bit lost with my code. I am uncertain about how to incorporate a success/error handler for the request. $resource('/example.json', {}, { get_something: method: 'POST' url: '/example/get_something.json& ...

What steps should I take to fix the error message "Uncaught TypeError: Class constructor m must be called with 'new'" that occurs while attempting to access a polymer v2.0 application?

Is there a way to resolve this error that occurs when attempting to open a Polymer v2.0 app on Safari in iOS? Uncaught TypeError: Class constructor m cannot be invoked without 'new' from custom-elements-es5-adaptor. The Polymer v2.0 starter k ...

Request made to Ajax fetching complete webpage content

I have a page full of random tips at http://www.javaexperience.com/tips To display these tips on other pages of the website, I am using an ajax call to add the content returned by the call to a specific div's HTML. The code for the div is: <div ...

Developing an Addon for Firefox using XUL and JavaScript

I am interested in creating a Firefox Addon that dynamically generates a button in the webpage's DOM when a specific page like www.google.com is loaded. This button, when clicked, will redirect to another page such as www.stackoverflow.com. It is imp ...

Efficiently processing multiple Ajax requests with a single callback function

I am currently facing a situation where I need to make multiple AJAX requests and only proceed if all of them are successful. The typical usage of $.when($.ajax(), [...]).then(function(results){},[...]); doesn't quite fit my needs because the number o ...

Enhancing Image Quality with jspdf and Html2Canvas

We are currently utilizing jsPDF and HTML2canvas to create PDFs, however, we have noticed that the image resolution is quite high. Is there a method available to obtain low-resolution images using jquery, javascript, jsPDF, and html2canvas? function addE ...

invoking a function by utilizing nested controllers

Struggling with nested controllers, the main goal of this code is to link data extracted from a .json file to another function or file. .html file: <div ng-app="myApp" ng-controller="GetCtrl" > <li ng-controller="ChannelCtrl" ng-repeat="x in ...

Every time an npm installation is attempted, the following error occurs: "npm ERR! Cannot read property 'resolve' of undefined."

Welcome Everyone! Currently, I am facing an issue on my dual boot system where Node and NPM were functioning smoothly on Windows 7. However, now that Windows 7 is not booting up, presumably due to hardware problems, I have resorted to using Windows 10. E ...

The implementation of Typescript in Express does not rely on Middleware

I've encountered an issue with my Auth Middleware - it seems that the middleware isn't being called at all. Even when I intentionally throw an Error within the middleware function, nothing is printed out. For testing purposes, I only need to inv ...

Import MDX metadata in Next.js on the fly

I am currently utilizing Next.js to create a static blog site. Following the guidelines in Next.js documentation, I set up @next/mdx and successfully imported MDX statically using import MDXArticle from "@/app/(article)/2023/test-article/page.mdx&quo ...

Does D3 iterate through the entire array every time we define a new callback?

It seems that every time a callback is set, d3 loops through the entire array. Initially, I thought that functions like attr() or each() were added to a pipeline and executed all at once later on. I was trying to dynamically process my data within d3&apo ...

unable to apply angular measurement inside quotation marks

What is the reason for this issue: <ul class="dropdown-menu"> <li ng-repeat="choice in dropDownItems"> <a class="btn" ng-click="mnuClick('{{choice}}')">{{choice}}</a> </li> </ul> However, this code wo ...

The function did not execute properly, resulting in the express route returning no value

Encountering some issues with Express routes that are behaving inconsistently despite having identical code execution. The goal is to have a client application make API calls like this: async search(){ const query = this.$refs.searchInput.value; ...

Learn how to retrieve information using the dash operator in ReactJS

I find it a bit amusing, but I'm encountering an issue. Can anyone lend me a hand with this? So, I'm using an API to fetch some data and it appears that the response from the API is in this format: start-time:2323232 end-time:2332323 Now, when I ...

Navigating through async functions in an Express.js router

Encountered a lint error indicating that Promises cannot be returned in places where a void is expected. Both functions [validateJWT, getUser] are async functions. Any suggestions on how to resolve this issue without compromising the linter guidelines by u ...

The conditional statement to check for an empty object does not trigger any actions

My goal is to display a success message once users successfully register without any errors. I have an errors reducer object in Redux that stores errors sent from the backend. The logic is set up so that if the errors object is empty, it shows the success ...

Fade out and slide close a div using jQuery

I am creating a new website and incorporating jQuery for animation and simplified JavaScript implementation. My goal is to have a button that, when clicked, will close a div with a fading out and slide up effect. Can this be achieved? Thank you. ...

Protractor quickly launches and closes the Chrome browser without completing the entire scenario

In order to test my application using protractor, I created a scenario. The application begins with a non-angular login page and then progresses to an angular page after logging in. Here is the javascript code snippet that was utilized: var chai = requir ...

What is the best way to filter out duplicate objects in JavaScript?

I have the following code snippet: let self = this; self.rows = []; self.data.payload.forEach(function (item, index) { if (!(self.rows.includes(item))) { self.rows.push(item); } }); The issue is that includes always returns false. Each ite ...