在角度我想在页面加载时只预填充todos数组一次并将此数组推入localStorage 然后,即使应用程序有页面刷新,它也可以通过添加和拼接功能进行修改
控制器代码
$scope.initializeGame = function () {
$scope.todos = JSON.parse(localStorage.getItem('todos')) || [];
*/ This is what I'm using to prepopulate the array but I only want it to do it once
and page refreshes creates new items
for(var i = 0 ; i < parseInt(2) ; i++)
$scope.todos.push({id:i, Index: i, Answered: 'No', Correct:'?'});
$scope.addTodo = function (){
$scope.todos.push({id:i, Index: i, Answered: 'Yes', Correct: '?'})
$scope.newTodo = ''
}
$scope.spliceTodo = function (){
$scope.todos.splice(1, 1, {id:i, Index: i, Answered: 'Yes', Correct: 'Correct'})
$scope.replaceTodo = ''
}
$scope.clearCompleted =function() {
$scope.todos = $scope.todos.filter(function(item){
return !item.done
})
}
$scope.$watch('todos',function(newValue, oldValue){
if(newValue!=oldValue){
localStorage.setItem('todos',JSON.stringify(newValue))
}
}, true)
}
HTML
<div >
<form name="frm" ng-submit="addTodo()">
<input type="text" name="newtodo" ng-model="newTodo" required />
<button >Add </button>
</form>
<form name="frm" ng-submit="spliceTodo()">
<input type="text" name="replaceTodo" ng-model="replaceTodo" required />
<button >Splice </button>
</form></div>