Angularjs 角度预填充数组仅一次
在angular中,我只想在页面加载时预填充todos数组一次,并将该数组推送到localStorage中 然后,即使应用程序有页面刷新,也可以通过添加和拼接功能对其进行干净的修改Angularjs 角度预填充数组仅一次,angularjs,Angularjs,在angular中,我只想在页面加载时预填充todos数组一次,并将该数组推送到localStorage中 然后,即使应用程序有页面刷新,也可以通过添加和拼接功能对其进行干净的修改 <div > <form name="frm" ng-submit="addTodo()"> <input type
<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>
控制器代码
$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)
<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>
$scope.initializeGame=函数(){
$scope.todos=JSON.parse(localStorage.getItem('todos'))| |[];
*/这就是我用来预填充数组的方法,但我只希望它执行一次
页面刷新将创建新项目
对于(var i=0;i
}
<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>
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>
添加
捻接
如果要保存到localStorage,在填充阵列之前,是否可以检查阵列是否已经存在?或者至少,在某个地方保存一个布尔值,告诉您在刷新页面时数组已经填充。如果($scope.todos.length!=0){for(var i=0;i