目标:
我希望localStorage缓存的答案数组仅在第一次加载时由4个对象var questions数组的内容预先填充 在后续页面刷新我想要加载修改后的localStorage答案数组,例如数组中可能还有更多的对象或拼接对象
每次页面刷新时,它都会恢复原来的4个对象数组。
var questions = [{"id":9,"Index":9,"Answered":"No","Correct":"?"},{"id":10,"Index":10,"Answered":"No","Correct":"?"},{"id":11,"Index":11,"Answered":"No","Correct":"?"},{"id":12,"Index":12,"Answered":"No","Correct":"?"}];
// storing our array as a string
localStorage.setItem("answers", JSON.stringify(questions));
// retrieving our data and converting it back into an array
var retrievedData = localStorage.getItem("answers");
// Possible Solution this intial array gets created every time the page refreshes and needs some logic to determine
// if it's intial length if not choose existing localstorage answers array in cache
$scope.answers = JSON.parse(localStorage.getItem('answers'))
$scope.addAnswer = function (){
$scope.answers.push({"id":10,"Index":10,"Answered":"Yes","Correct":"Correct"})
$scope.newAnswer = ''
}
$scope.spliceAnswer = function (){
$scope.answers.splice(1, 1, {"id":10,"Index":10,"Answered":"Yes","Correct":"InCorrect"})
$scope.replaceAnswer = ''
}
$scope.$watch('answers',function(newValue, oldValue){
if(newValue!=oldValue){
localStorage.setItem('answers',JSON.stringify(newValue))
}
}, true)
HTML
<form name="frm" ng-submit="addAnswer()">
<input type="text" name="newAnswer" ng-model="newAnswer" required />
<button >Add </button>
</form>
<form name="frm" ng-submit="spliceAnswer()">
<input type="text" name="replaceAnswer" ng-model="replaceAnswer" required />
<button >Replace </button>
</form>
<h6>Answers : {answers}</h6>
答案 0 :(得分:0)
我认为问题在于:
if(newValue!=oldValue){
localStorage.setItem('answers',JSON.stringify(newValue))
}
验证您的新旧值,将其更改为:
if(newValue && oldValue && newValue!=oldValue){
localStorage.setItem('answers',JSON.stringify(newValue))
}
答案 1 :(得分:0)
$scope.key = ($cookieStore.get('arraySize')) ? ($cookieStore.get('arraySize')) :0 ;
$scope.$watch('key', function () {
if($scope.key == 0) {
localStorage.setItem("answers", JSON.stringify(questions));
} else{
$scope.answers = JSON.parse(localStorage.getItem('answers'));
}
});
$scope.$watch('answers',function(newValue, oldValue){
if(newValue!=oldValue){
localStorage.setItem('answers',JSON.stringify(newValue))
$scope.size = (JSON.parse(localStorage.getItem('answers'))).length;
$cookieStore.put( 'arraySize' , $scope.size );
}
}, true)
$scope.arrayLength = $cookieStore.get('arraySize');
$scope.key = parseInt($cookieStore.get('arraySize'));