Reputation: 43
I store some data in a localstorage in my Javascript file. I want to create a delete button on the details grid that allows me to delete an individual item. I need to first identify the key of the selected item and then use the localStorage.removeItem(key)
method to delete the item. But my method doesn't seem to work.
This is in my factory:
removeItem: function (data) {
var prefixLength = prefix.length;
Object.keys(localStorage)
.forEach(function (key) {
if (key.substring(0, prefixLength) == data) {
var item = window.localStorage[key];
localStorage.removeItem(key);
}
});
},
Then I call it in my controller.js:
$scope.remove = function () {
expService.removeItem($scope.expense);
},
my button is:
<button type="button"class="btn btn-sm btn-danger pull-right" id="remove" ng-click="remove()">
<span class="glyphicons glyphicons-bin"></span>
</button></div>
Upvotes: 1
Views: 1799
Reputation: 3427
In my case, I had to delete a localstorage data on button click. Here is how I achieved that.
<button onclick="deleteFavorite('Id or name what you set as key')"> Delete </button>
function deleteFavorite(Id){
localStorage.removeItem(Id);
}
Please note that you can add id dynamically to the function using javascript and you have to reload the page to see if the item is deleted or not.
Upvotes: 1
Reputation: 26
localStorage.removeItem('itemTodelete');
localStorage.remove('itemTodelete'); or
localStorage.clear();
Upvotes: 0
Reputation: 8884
I didnt see error but simple to do it
<button type="button"class="btn btn-sm btn-danger pull-right" id="remove" ng-click="remove(expense)">
<span class="glyphicons glyphicons-bin"></span>
</button>
and js
$scope.remove = function (itemTodelete) {
localStorage.removeItem(itemTodelete);
},
Upvotes: 0