简体   繁体   中英

Toggle button with value from sessionStorage

I have a small toggle button, and I store value (true or false) to sessionStorage, and on page load, if the value exists in sessionStorage I take it and show toggle button depending on value, also, depending on this value I show different content on my angularjs page.

Problem is, I store a value to sessionStorage, and on again I call this value but my toggle button and my ng-if statement do not get this. Here is my code bellow.

Question is, how, and why I can't get this to the ng-if statement? (in my fiddle I use ng-show because ng-if not working in this example)

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> 

A few issues:

First, in your fiddle, you're using AngularJS version 1.1.1. ng-if did not exist in AngularJS prior to version 1.1.5. So you'll want to update your AngularJS version to use ng-if .

Secondly, sessionStorage can only accept string values. So if you want to store a JS object in sessionStorage , you have to JSON.stringify() the object to store it, and use JSON.parse() when retrieving it.

Finally, your conditional block always sets $scope.basicMode to true :

if (sessionStorage.getItem("modePreview")) { // if modePreview is true
  $scope.basicMode = sessionStorage.getItem("modePreview"); // set basicMode to true
} else { // otherwise, still set basicMode to true?
  $scope.basicMode = true;
}

I think you want the else statement to be $scope.basicMode = false , right?

Updated Working Fiddle: https://jsfiddle.net/zx02f1yv/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM