This is my ctrl:
app.controller(\'ctrl\', function ($window, $scope) {
$scope.initData = [
{
firstName: \"John\",
lastNa
delete data from local storage using JavaScript Here is your code without error passed.
use function for delete
function deleteRow(index){
dataList.splice(index, 1);
console.log('====>', dataList)
localStorage.setItem('items', JSON.stringify(dataList));
}
This code will help you to understand.....
<!DOCTYPE html>
<html>
<head>
<script>
var ArrayData = [];
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (localStorage.count) {
localStorage.count = Number(localStorage.count)+1;
} else {
localStorage.count = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.count;
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
function load()
{
var odser = JSON.parse(localStorage.getItem("data"));
document.getElementById("result1").innerHTML = odser;
}
function fun()
{
var odser = JSON.parse(localStorage.getItem("data"));
ArrayData = odser;
ArrayData.push(3);
var oser = JSON.stringify(ArrayData);
localStorage.setItem("data", oser);
var odser = JSON.parse(localStorage.getItem("data"));
document.getElementById("result1").innerHTML = odser;
}
</script>
</head>
<body onload="load()">
<button onclick="clickCounter()" type="button">Click me!</button>
<button onclick="fun()" type="button">Click me! Array</button>
<div id="result"></div>
<div id="result1"></div>
</body>
</html>
In Simple Steps in matters how you need your page to refresh using afunction to refresh comes handy and effective for me and keeps the locaStorage values set.. i used.... the function below by calling it as load() and it worked for me
function load()
{
console.log("loading")
setTimeout("window.location.assign('samepage.html');", 1000);
}
You need to check first if your localStorage is empty on load
if (localStorage == null) {//setItem() ...};
Your line $window.localStorage.setItem('initData', JSON.stringify($scope.initData));
is resetting the data each time you refresh.
Replace the line with this:
if(!localStorage.getItem('initData')){
$window.localStorage.setItem('initData', JSON.stringify($scope.initData));
}
More over you should not have that line at all. Start with an empty local storage and add new entries from UI only.
The above code only run it once, for the first time the application is run.
If yo want to re-insert the data every time the list is empty then try following
if(!localStorage.getItem('initData') || JSON.parse(localStorage.getItem('initData')).length === 0){
$window.localStorage.setItem('initData', JSON.stringify($scope.initData));
}
On every page load you are setting new initData and updating the local storage... Instead you should check for existing localstorage data and use that before using the mocked initData