Storing a string in localStorage versus $localStorage in Angular 1 yields distinct value differences

I have encountered an issue in my angular controller where I am trying to save a token returned from an API endpoint as a string. In this example, I have used the variable testData instead of the actual token.

var testData = "testdata"

$localStorage['jwtToken'] = testData
localStorage.setItem('jwtToken',testData)

Here is what is stored for the first line:

{"ngStorage-jwtToken" : ""testdata""}

And now for the second line:

{"jwtToken" : "testdata"}

The key changing makes sense to me, but I'm puzzled by the double quotes surrounding the data string in the value of the key in the first line. Has anyone faced this issue before? Is there something wrong with my approach?

Below is the code snippet:

angular.module('app', [
  'ngAnimate',
  'ngAria',
  'ngCookies',
  'ngMessages',
  'ngResource',
  'ngSanitize',
  'ngTouch',
  'ngStorage',
  'ui.router'
]);

app.controller('SigninFormController', ['$scope', '$http', '$state', '$localStorage',
  function($scope, $http, $state, $localStorage) {
    $scope.user = {};
    $scope.authError = null;
    $scope.login = function() {
      $scope.authError = null;
      // Attempting to login
      $http.post('api/auth/login', {
          email: $scope.user.email,
          password: $scope.user.password
        })
        .then(function(response) {
          if (response.status = 200 && response.data.token) {

            var testData = "testdata"

            $localStorage['jwtToken'] = testData
            localStorage.setItem('jwtToken', testData)

            /*
                $localStorage['jwtToken'] = response.data.token
                localStorage.setItem('jwtToken',response.data.token)
                */

            $state.go('app.home');
          } else {
            $scope.authError.message
          }

        }, function(err) {
          if (err.status == 401) {
            $scope.authError = err.data.message
          } else {
            $scope.authError = 'Server Error';
          }
        });
    };
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>

<body ng-controller="">
  <div class="container w-xxl w-auto-xs" ng-controller="SigninFormController">

  <div class="m-b-lg">
    <div class="wrapper text-center">
      <strong>Sign in to get in touch</strong>
    </div>
    <form name="form" class="form-validation">
      <div class="text-danger wrapper text-center" ng-show="authError">
        {{authError}}
      </div>
      <div class="list-group list-group-sm">
        <div class="list-group-item">
          <input type="email" placeholder="Email" class="form-control no-border" ng-model="user.email" required>
        </div>
        <div class="list-group-item">
          <input type="password" placeholder="Password" class="form-control no-border" ng-model="user.password" required>
        </div>
      </div>
      <button type="submit" class="btn btn-lg btn-primary btn-block" ng-click="login()" ng-disabled='form.$invalid'>Log in</button>
      <div class="text-center m-t m-b"><a ui-sref="access.forgotpwd">Forgot password?</a></div>
      <div class="line line-dashed"></div>
      <p class="text-center"><small>Do not have an account?</small></p>
      <a ui-sref="access.signup" class="btn btn-lg btn-default btn-block">Create an account</a>
    </form>
  </div>
  <div class="text-center" ng-include="'tpl/blocks/page_footer.html'">
  
  </div>
</div>
</body>

Answer №1

Reason for enclosing string in double quotes

To easily extract the correct object, array, or string from storage without having to determine the types, developers often encapsulate the data within double quotes. This allows them to utilize JSON.parse() method effectively.

Here is a basic representation:

localStorage.setItem('xxx', '"testData"');
var val1 = JSON.parse(localStorage.getItem('xxx'));

localStorage.setItem('yyy', '{"foo": "bar"}');
var val2 = JSON.parse(localStorage.getItem('yyy'));

Purpose of prepending the key name with 'ngStorage'

By adding 'ngStorage' at the beginning of the key names, developers can differentiate between Angular-specific keys and other keys in localStorage. This way, they can easily iterate over the keys and populate their objects accordingly.

var myStorage = {};
Object.keys(localStorage).forEach(function(key){
    if (key.indexOf("ngStorage")===0) {
       myStorage[key.substr(10)] = JSON.parse(localStorage[key]);
    }
});

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 it possible to generate a triangular attachment below a div element?

My designer sent me a unique design and I'm wondering if it's possible to replicate using HTML, CSS, or JavaScript? https://i.stack.imgur.com/spB71.png I believe it can be done with CSS by creating a separate div positioned absolutely under the ...

You cannot reassign NodeJS global variables

Currently, I am in the process of writing unit tests for code that utilizes a JavaScript library. This particular library sets a global variable if it does not already exist using the following pattern: var GLOBAL_VAR = GLOBAL_VAR || {} While this method ...

Ensure the text value of a collection of web elements by utilizing nightwatch.js

Recently, I started using nightwatch.js and I am trying to retrieve a list of elements to verify the text value of each element against a specific string. Here's what I have attempted: function iterateElements(elems) { elems.value.forEach(funct ...

The term 'MapEditServiceConfig' is being incorrectly utilized as a value in this context, even though it is meant to refer to a type

Why am I receiving an error for MapEditServiceConfig, where it refers to a type? Also, what does MapEditServiceConfig {} represent as an interface, and what is the significance of these brackets? export interface MapEditServiceConfig extends AppCredenti ...

Error message displayed: "An error occurred while processing the VueJS InertiaJS Uncaught (in promise) TypeError. It seems that the property 'search'

Currently, I am working on a Vue JS project with Inertia. One of the features I am implementing is a list that allows users to filter by name. data() { return { selectedUser: this.value, selected: null, search: & ...

Unable to use npm module "csv-db" as it is currently experiencing functionality issues

Looking to implement a "lightweight offline database" that stores data in .csv files. The module I am using can be found in the documentation: https://www.npmjs.com/package/csv-db Unfortunately, I've been encountering issues with this module and have ...

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

Ways to conceal the form utilizing ng-click?

I have created a search form that displays product details when the ng-click button is clicked. After receiving the product details, I wish to hide the form. product.html <form name="search_form"> <div class="search" flex layout="row" layout-a ...

What causes the v-for in a template to only update when the input text changes?

I'm currently working on a Vue.js code, but I'm facing an issue where the template isn't updating when new data is added to the input text. My goal is for the list to update when the @click event occurs. Visit this link for reference metho ...

Processing images with PHP from an array using AJAX

I have designed a straightforward form for image uploading. I am storing the properties of the uploaded images in an array, and my goal is to send this array to a PHP file using ajax. However, when I attempt to access the uploaded image using $_FILES[&apos ...

Counting radio buttons in AngularJS and handling undefined values when passing parameters

After spending countless hours trying to figure out how to count radio buttons, I encountered another issue where the value passed to ng-change would become "undefined". My question is, how can I successfully pass that value? Any assistance with counting o ...

Angular 7+: Trouble with displaying images from assets directory

Details regarding my Angular version: Angular CLI: 7.3.9 Node: 10.15.3 OS: win32 x64 Angular: 7.2.15 ... animations, common, compiler, compiler-cli, core, forms ... language-service, platform-browser, platform-browser-dynamic ... rout ...

Guide on displaying a real-time "Last Refreshed" message on a webpage that automatically updates to show the time passed since the last API request

Hey all, I recently started my journey into web development and I'm working on a feature to display "Last Refreshed ago" on the webpage. I came across this website which inspired me. What I aim to achieve is to show text like "Last Refreshed 1 sec ago ...

Dynamic AJAX Dependent Dropdown Menu

Can you help me create a dynamic input form? I need assistance in creating an input form with a dynamic dropdown list, similar to the screenshot provided below: https://i.stack.imgur.com/rFSqV.png What is my current script setup? The script I have is d ...

Passing data between multiple components in Vue.js and Laravel: Best practices

require('./bootstrap'); window.Vue = require('vue'); Vue.component('exampleComponent1', require('./components/exampleComponent1.vue')); Vue.component('exampleComponent2', require('./components/exampl ...

Ways to layer two divs on each other and ensure button functionality is maintained

In the process of developing a ReactJS project, I encountered the challenge of overlapping my search bar autocomplete data with the result div located directly below it. For a more detailed understanding, please take a look at the provided image. Here&apo ...

Observable<void> fails to trigger the subscriber

I am currently facing a challenge with implementing a unit test for an Observable in order to signal the completion of a process. While there is no asynchronous code in the logout function yet, I plan to include it once the full logic is implemented. The m ...

Laravel does not have the capability to provide a genuine json response

I am facing an issue with my Laravel controller. The code is straightforward: class MyController extends Controller { public function list() { return response()->json(['a' => 'hello']); } } When I access the ...

Displaying XML data using d3js

Currently, I am working on a d3.js assignment for my school project. While looking at some examples to load an XML file, I seem to be encountering difficulties in figuring out what's going wrong. The XML file is loading correctly, but as I am still le ...

The ultimate guide to personalizing group titles in Angular UI-Select

Is there a way in Angular ui-select to customize the group label? I want to make it larger than the selection items as shown in the image below. https://i.stack.imgur.com/ofcak.png The list is currently grouped by country, but how can I adjust the size o ...