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)
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>