【问题标题】:How to save dynamic checkbox state after page refresh?页面刷新后如何保存动态复选框状态?
【发布时间】:2017-08-10 02:20:44
【问题描述】:

即使在刷新页面后,我仍在尝试保存复选框的状态。我可以获得每个动态复选框的索引,因此我知道选中了哪个复选框,但是即使在页面刷新后我也无法使复选框保持不变。我尝试使用 localStorage 在本地保存,即使它存储了值,它也不会保持复选框状态相同:

动态复选框 HTML:

<input type="checkbox" ng-model="checkbox[$index]" ng-change="alert($index)">

获取动态复选框索引:

$scope.checkbox = []; //checkbox index
$scope.alert = function(index, event){
  localStorage['checkbox'] = $scope.checkbox[index];
  alert("checkbox " + index + " is " + $scope.checkbox[index]);

}

//检查更改并更新

localStorage.getItem("checkbox") ? 
JSON.parse(localStorage.getItem("checkbox")) : false;

$scope.$watch(localStorage['checkbox'], function (newVal, oldVal) {
  if (oldVal !== newVal) {
    localStorage['checkbox'] = newVal;
  }
});

【问题讨论】:

  • 您需要在init上分配值,检查localstorage是否有信息,然后分配给每个检查。

标签: javascript angularjs checkbox local-storage


【解决方案1】:

试试这个sn-p,如果有信息需要从本地存储的内容循环并分配给每个复选框。

HTML 示例

<p ng-repeat="check in checkBoxes track by $index">
  <label>{{$index}}</label>
  <input type="checkbox" ng-model="checkBoxes[$index]" ng-change="valueChange()"/>
</p>

<pre>{{checkBoxes}}</pre>    

控制器上的示例

$scope.checkBoxes = [false, false, false, false];

if(localStorage['checkBoxes']){
  $scope.checkBoxes = JSON.parse(localStorage.getItem("checkBoxes"));
  console.log(localStorage['checkBoxes'].length);
}

$scope.valueChange =function(){
  localStorage.setItem("checkBoxes", JSON.stringify($scope.checkBoxes));
};

Sample Plnkr

【讨论】:

  • 但它如何记住我在刷新页面后选择了哪个复选框?
  • 让我做个 plnkr。
  • 检查 plnkr,如果满足用例,请告诉我。
  • 谢谢@jesus-carrasco。这就是我一直在寻找的。​​span>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
  • 2020-09-16
  • 1970-01-01
  • 2011-03-11
  • 2021-03-01
  • 1970-01-01
  • 2021-02-07
相关资源
最近更新 更多