我从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>
现在,如果您选中此框并重新加载页面,则该复选框将再次变为未选中状态。
即使重新加载后,如何使复选框保持其值呢?谢谢!
答案 0 :(得分:1)
即使您重新启动浏览器,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>