Angularjs:如何在重新加载后保留复选框值

Angularjs: How to keep checkbox value after reload

我从 W3Schools 获得了以下代码,但我想知道如何让复选框值在页面重新加载后仍然存在:

Keep HTML: <input type="checkbox" ng-model="myVar">

<div ng-if="myVar">
<h1>Welcome</h1>
<p>Welcome to my home.</p>
<hr>
</div>

<p>The DIV element will be removed when the checkbox is not checked.</p>
<p>The DIV element will return, if you check the checkbox.</p>

现在,如果您选中该框并重新加载页面,该复选框将再次变为未选中状态。

如何让复选框在重新加载后仍保留其值?谢谢!

即使您重新启动浏览器,localStorage 也会存储您的信息...我认为这会更适合...以下代码适用于您的本地环境

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

  let existingStoredValue = localStorage.getItem("checkBox Value");
  if (existingStoredValue == 'true') {
    $scope.myVar = true;
  }

  $scope.storeCB = function(passedVal) {
    localStorage.setItem("checkBox Value", passedVal);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

  Keep HTML: <input id='keepHTML' type="checkbox" ng-model="myVar" ng-click="storeCB(myVar)">

  <div ng-if="myVar">
    <h1>Welcome</h1>
    <p>Welcome to my home.</p>
    <hr>
  </div>

  <p>The DIV element will be removed when the checkbox is not checked.</p>
  <p>The DIV element will return, if you check the checkbox.</p>
</div>