使用sessionStorage中的值切换按钮

时间:2019-02-08 13:11:04

标签: javascript angularjs

我有一个小的切换按钮,我将值(true或false)存储到sessionStorage,并且在页面加载时,如果该值存在于sessionStorage中,则根据值(也取决于此值)将其显示并显示切换按钮我在angularjs页面上显示了不同的内容。

问题是,我将一个值存储到sessionStorage,然后再次调用此值,但是我的切换按钮和ng-if语句没有得到此值。这是下面的代码。

问题是,如何以及为什么我不能在ng-if语句中使用它? (在我的小提琴中,我使用ng-show是因为ng-if在此示例中不起作用)

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>

1 个答案:

答案 0 :(得分:1)

一些问题:

首先,在您的小提琴中,您正在使用AngularJS 1.1.1版。 ng-if在1.1.5版之前的AngularJS中不存在。因此,您需要更新AngularJS版本以使用ng-if

第二,sessionStorage仅接受字符串值。因此,如果要将JS对象存储在sessionStorage中,则必须JSON.stringify()个对象来存储它,并在获取它时使用JSON.parse()

最后,您的条件块始终将$scope.basicMode设置为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;
}

我认为您希望else语句为$scope.basicMode = false,对吧?

更新的工作小提琴:https://jsfiddle.net/zx02f1yv/