Switch button displaying stored data in sessionStorage

I am facing an issue with my small toggle button in AngularJS. I have set up sessionStorage to store a value (true or false), and upon page load, I retrieve this value from sessionStorage to display the toggle button accordingly. Depending on the value stored, I also show different content on my AngularJS page.

The problem arises when I try to access this stored value for my ng-if statement. Despite storing the value in sessionStorage, the toggle button and ng-if statement do not seem to recognize it. Below is the code snippet for reference.

Could someone help me figure out why the ng-if statement is not working as expected? (I have used ng-show in the provided fiddle example due to limitations)

working fiddle

var app = angular.module("ap", []);

app.controller("con", function($scope) {
  if (sessionStorage.getItem("modePreview")) {
    $scope.basicMode = sessionStorage.getItem("modePreview");
  } else {
    $scope.basicMode = true;
  }
  $scope.sendModeValueToStorage = function() {
    sessionStorage.setItem(
      "modePreview",
      ($scope.basicMode = !$scope.basicMode)
    );
  };

});
.activeSwitch,
.inactiveSwitch {
  font-size: 26px;
  cursor: pointer;
}

i.activeSwitch {
  color: #e4e4e471;
}

i.inactiveSwitch {
  color: #e4e4e471;
}

.fontStyleUserControlPannel {
  font-size: 18px;
  font-weight: 600;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<body ng-app="ap" ng-controller="con">

  Advanced mode <i class="fa fa-toggle-on fa-2x" ng-click="sendModeValueToStorage()" ng-class="{'fa-rotate-180' : basicMode}"></i> Basic mod

  <div ng-show="!basicMode">
    <h3>
      Basic mode
    </h3>
  </div>
  <div ng-show="basicMode">
    <h3>
      Advanced mode
    </h3>
  </div>
</body>

Answer №1

There are a few issues that need to be addressed in your code:

First, it appears that you are using AngularJS version 1.1.1 in your fiddle. However, the ng-if directive was not introduced until AngularJS version 1.1.5. Therefore, I recommend updating your AngularJS version to at least 1.1.5 in order to use ng-if.

Secondly, please keep in mind that sessionStorage can only store string values. If you intend to store a JavaScript object in sessionStorage, you will need to first use JSON.stringify() to convert the object into a string before storing it. When retrieving the object from sessionStorage, remember to use JSON.parse() to convert it back into an object.

Lastly, there is an issue with your conditional block where $scope.basicMode is always being set to true:

if (sessionStorage.getItem("modePreview")) {
  $scope.basicMode = sessionStorage.getItem("modePreview");
} else {
  $scope.basicMode = true;
}

It seems like you may want to update the else statement to $scope.basicMode = false instead of setting it to true. Is that correct?

For a working example, please refer to this updated fiddle: https://jsfiddle.net/zx02f1yv/

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

The array in this.props (passed down by redux) comes back as undefined

To fetch data using Redux in my component, I follow this approach: import React, {Component} from 'react'; import {bindActionCreators} from 'redux'; import {connect} from 'react-redux'; import * as actionCreators from '. ...

The error encountered is related to the MongooseServerSelectionError that occurs in

I have been working on setting up my first mongo-db application to connect to the server. However, I am encountering a specific error during this process: const express = require('express'); const mongoose = require('mongoose'); const ...

Remove the most recent row that was dynamically inserted into an HTML table

Currently, I am in the process of developing an ASP.NET Web Api 2.2 application using .NET Framework 4.5, C#, and jQuery. Within one of my views, I have set up the following table: <table id ="batchTable" class="order-list"> <thead> ...

react-datepicker displaying error message "Preventing default action not possible within a passive event listener invocation"

I've integrated the react-datepicker library in portal mode. While it functions well on browsers, I encounter an error when using mobile browser mode. An issue arises stating: "Unable to preventDefault inside passive event listener invocation" Des ...

jQuery menu fails to toggle the class name

The toggle functionality in the Menu is not working properly. Upon clicking the toggle button, I encountered the following JavaScript error: "message": "Uncaught TypeError: Cannot read property 'toggle' of undefined", "filename": "https://st ...

Check if the input values are already in the array and if not, then add

Within my React application, I am displaying an Array and each entry in the Array is accompanied by an input element. These input elements are assigned a name based on the entry's ID, allowing users to enter values. To handle the changes in these inp ...

Guidelines for capturing a div screenshot with javascript

Let's say I have a div containing an image source. <div> <p class="row">With custom CSS</p> <img src="/images/midhun.jpg"> </div> When a button is clicked, I want to display a screenshot of this image in another div. C ...

An exploration of effortlessly moving elements using webdriver.io - the power of

I have been attempting to utilize the drag and drop method in WebDriver.io, but I am encountering issues. I followed the example for drag & drop on this website: https://www.w3schools.com/html/html5_draganddrop.asp. This functionality is essential for ...

The md-datepicker component is disregarding the specified custom margin

For my project, I am implementing the AngularJS Material datepicker. However, I have encountered an issue with custom CSS not being applied to the md-datepicker. If you want to see a demo, check out this link: Demo Here's a brief code snippet that d ...

Issue Arising During File Transfer in Nativescript

I am currently attempting to upload an image that I captured with Nativescript to a server using a web API that I created in C# (ASP.NET). The API works perfectly fine when tested on Postman, but I encounter an error "Error During Upload" while trying to u ...

Having trouble with a peculiar for_of loop issue in Node.js: struggling to iterate correctly

Currently immersed in a Python project, I find myself in need of retrieving data from a Node.js API. Despite my limited knowledge of Node.js, I attempted to write some code for this purpose. Here is the code snippet: const SneaksAPI = require('sneaks ...

Addressing the Cross Domain Issue when Implementing DHIS 2 API with jQuery

Today, I spent hours trying to authenticate my javascript application with the DHIS 2 API using Jquery. According to the API documentation (https://www.dhis2.org/doc/snapshot/en/user/html/ch32s02.html), base 64 authentication is required. However, my attem ...

Instructions on transforming an img into an Image component within next.js

I have successfully implemented all the logic in this component, tailored to the <img> tag. Now, I am aiming to apply the same logic to the Image component. However, when attempting to do so, I encounter an error. TypeError: Failed to construct &apos ...

Techniques for capturing Django's output from an Ajax request

I've been trying to utilize Ajax for converting my form data to JSON and sending it to my Django view. However, I'm encountering an issue where after successful processing in the view, I am returning a template response with some context data tha ...

Activate audio and trigger notification

I'm looking to incorporate a small beep sound into my web application before displaying an alert message. Here's what I currently have: if(_none_valid) { $.playSound('/static/wav/beep_error.wav').delay(300); alert('ERROR: ...

"Unexpected behavior: Angular route parameters are found to be empty upon receiving the API

Seeking to extract parameters from the urlcallback received from an external authentication source, within my Angular project using angular-route/$routeProvider The API redirect is as follows: http://localhost:8080/dist/?somevar=someval&val2=someot ...

Setting up Laravel with pjax

For the first time, I am experimenting with using pjax in combination with Laravel to enhance page loading speed. Since I am not well-acquainted with this technology yet, I have integrated this package into my project. Everything appears to be functioning ...

How can we customize HTML images without allowing third-party JavaScript to enlarge them?

I am using Blogger to host my website and I have a basic knowledge of HTML and CSS. I want to incorporate a collaborative add-your-link feature using SimplyLinked. However... They provided me with the following HTML: <script type="text/javascript" src ...

What are the steps to generate an npm package along with definition files?

Is it possible to create an NPM package with definition files containing only interfaces declared in *.ts files? Consider a scenario where we have two interfaces and one class definition: export interface A { id: number; } export interface B { name: s ...

Error Encountered with Next.js 13.4.1 when using styled-components Button in React Server-Side Rendering

I am currently working on a React project using Next.js version 13.4.1 and styled-components. One problem I'm facing is with a custom Button component that I've created: import React from 'react'; import styled from 'styled-compone ...