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

Looking for assistance with reviewing and optimizing Angular UI-Router implementation

I'm currently facing an issue with setting up routing for my angular portfolio. Despite checking my code against a previous app, I am unable to identify the error as there are no console logs when I compile. Can someone please review my code layout an ...

A guide on dragging a box using JavaScript

I recently came across a box similar to the one in the image below: <div id="HelpDoc"> <div id="HelpHeader">Here goes the header</div> <div id="HelpContent">Here goes the content</div> </div> I am looking for a ...

How can I access a PHP variable from an external .php file within a JavaScript script?

I have recently implemented a JavaScript code called "upload.js" for uploading files to my server: function beginUpload(){ document.getElementById('upload_form').style.visibility = 'hidden'; return true; } function endUpload(s ...

Using HTML to execute a JavaScript function that transforms images

The script cutImageUp has been previously discussed on SE in a thread about Shattering image using canvas. However, I have encountered a different issue while attempting to use it. The HTML code I implemented seems to be ineffective, and despite my efforts ...

Construct a div element using JSON information

I am retrieving information from a database and organizing it into a JSON array. Here is the data that I have: [{"id":"0","name":"red","percentage":"60"},{"id":"1","name":"blue","percentage":"58"},{"id":"4","name":"green","percentage":"12"}] The structu ...

Update the default base URL configuration for Axios

My axios configuration looks like this: const configAxios = { baseURL: 'http://127.0.0.1:8000/api', timeout: 30000, }; Vue.prototype.$axios = axios.create(configAxios) When making a call inside my component, I use the following syntax: this ...

Routing with nested modules in Angular 2 can be achieved by using the same

Encountering a common issue within a backend application. Various resources can be accessed through the following routes: reports/view/:id campains/view/:id suts/view/:id certifications/view/:id Note that all routes end with the same part: /view/:id. ...

Is there a way to ensure my Vue variable is declared once the page has fully loaded?

I have implemented a v-for loop in my code: <div v-for="(user, index) in users" :key="index" :presence="user.presence" class="person"> <span class="cardName h4">{{ user.name }}</span> ...

What is the simplest method for preserving the Redux state?

What is the most efficient method to maintain state in Redux even after a website refresh? I would prefer not to rely on redux-persist if there are alternative options available. ...

Initiating an Ajax POST request by clicking a button

I have a button on my webpage that, when clicked, currently prints the value of an element to the console using a basic function. Instead of just printing the value, I want to update my Django view by sending it through a POST request. Here's the cu ...

Exploring VueJS Router History Mode with NGinx web server

After conducting research, I discovered several issues similar to the one I am facing. Currently, I have a docker-compose setup on Digital Ocean with NGinx, VueJS, and a Static Landing Page. Everything was working fine until I added a new route with a fo ...

The DOM is failing to refresh in Vue.js even after the array has been updated

After receiving a list of items using AJAX, I store them in a data Array: loadSparepartFiles: function() { var vm = this; vm.activeSparepart.attachments = []; ajaxApi.loadJson('spareparts/sparepart/getFiles/'+vm.activeSparepartId, fu ...

Leveraging personalized design elements from a theme in Material UI without the need for makeStyles

Is there a way to access the theme.customElements.actionButton in MyComponent without relying on makeStyles? For instance, can I directly use className={theme.customElements.actionButton}? theme.js const theme = createMuiTheme({ customElements: { ...

Having trouble converting response.data to a string in ReactJS

import React, { Component } from 'react' import TaskOneServices from '../services/TaskOneServices' import circle from '../assets/icons/dry-clean.png' import tick from '../assets/icons/check-mark.png' async function ...

Creating dynamic HTML table rows with data from a JSON object

Query: In search of a Jquery or JavaScript solution for generating dynamic table rows with colspan using the JSON structure provided below. I am encountering difficulties in creating the necessary rows and have attempted several approaches without success ...

What is the process for configuring the .htaccess file to navigate to https:// in an Angular application?

I have come across similar solutions for access issues, but they seem to impact the routes themselves. Would it not be simpler to just update the initial load to use HTTPS and let everything else follow suit from there? The structure of my site is as foll ...

Tips for modifying the language of an Angular Application's OneTrust Cookie Banner

I'm currently developing an Angular application and utilizing OneTrust for managing cookie consent. The issue I'm encountering is that while the rest of the components on the login page are properly translated into the target language, the OneTru ...

Tips for adjusting the border color of a MUI Select field

https://i.stack.imgur.com/rQOdg.png This MUI select box changes color from blue to black based on selection. The challenge is to customize the text and border color to white (currently set as blue). Any suggestions on how to achieve this? ...

Is it possible to use a server action in Next.js to both retrieve data and refresh the page?

I am currently working on developing a web application using Next.js (13.4.9) and I intend to utilize server actions. These server actions will involve sending data to the server, which will process the data and return a string back to me. The challenge I& ...

Filtering data in Laravel can be efficiently achieved by utilizing Laravel's ORM hasmany feature in conjunction with Vue

Hey there, I'm currently working with Laravel ORM and Vue 2. I've encountered some issues with analyzing Json data. Here's my Laravel ORM code: $banner = Banner::with('banner_img')->get(); return response()->json($banner); ...