This is my ctrl:
app.controller('ctrl', function ($window, $scope) {
$scope.initData = [
{
firstName: "John",
lastName: "Doe",
},
{
firstName: "Jane",
lastName: "Doe",
},
{
firstName: "John",
lastName: "Smith",
}
];
$window.localStorage.setItem('initData', JSON.stringify($scope.initData));
$scope.retrievedData = JSON.parse($window.localStorage.getItem('initData'));
$scope.sortedType = 'firstName';
$scope.sortedReverse = false;
//Remove Rows and Update localStorage Key Values
$scope.removeRow = function(row) {
$scope.retrievedData.splice(row, 1);
$scope.initData.splice(row, 1);
$window.localStorage.setItem('initData', JSON.stringify($scope.initData));
}
});
HTML:
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>
<span ng-show="sortedType == 'firstName' && sortedReverse" class="fa fa-long-arrow-up"></span>
<span ng-show="sortedType == 'firstName' && !sortedReverse" class="fa fa-long-arrow-down"></span>
<span href="#" ng-click="sortedType = 'firstName'; sortedReverse = !sortedReverse" style="cursor:pointer;">First Name</span>
</th>
<th>
<span ng-show="sortedType == 'lastName' && sortedReverse" class="fa fa-long-arrow-up"></span>
<span ng-show="sortedType == 'lastName' && !sortedReverse" class="fa fa-long-arrow-down"></span>
<span href="#" ng-click="sortedType = 'lastName'; sortedReverse = !sortedReverse" style="cursor:pointer;">Last Name</span>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(k, v) in retrievedData | orderBy: sortedType: sortedReverse">
<td>{{v.firstName}}</td>
<td>{{v.lastName}}</td>
<td>
<button class="btn btn-primary">Edit</button>
<button class="btn btn-primary" ng-click="removeRow();">Delete</button>
</td>
</tr>
</tbody>
</table>
Now, I believe it is clear what this does. It is assigning a data from $scope.initData
to localStorage
and then interpolate it into the HTML. the function removeRow()
deletes the row in the table and updates the localStorage
with the latest action. The issue with this is that each time I reload the HTML the initial localStorage
data gets loaded and not the updated one. I know that this is because I'm assigning it here: $window.localStorage.setItem('initData', JSON.stringify($scope.initData))
; but I don't know how to keep it updated after the refresh.
Please advise.
Thanks.