javascriptangularjshtmllocal-storageng-storage

Value in table is not getting updated after updating $localStorage data in AngularJS


I have two components in AngularJS. One component usersList contains a table

<table>
  <tbody>
    <tr ng-repeat="..."><!--Contains code to repeat the entries in usersList localstorage object--></tr>
  </tbody>
</table>

On page load, this component fetches a list of users with their details from an API and stores it in $localStorage. Other is a form editUserProfile where the values are edited and deleted

app.component("editUserProfile", {
  ...
  controller: function($localStorage, ...) {
    vm.$storage = $localStorage;
    // Do other things
    // Some event (edit) is successful, update the userslist in $localStorage
    vm.$storage.usersList = response
  }
})

So basically, I am editing user details and deleting users by making calls to the API, and when a successful edit/delete happens, I refresh the $localStorage value of usersList which is a JSON object.

Things totally works till the updating of the data, however the changes are not reflected in the usersList component. I am doing this to save calls to the API for just displaying the data. Any other ideas are welcome.


Solution

  • See this Plunkr working.

    var app = angular.module('app', ['ngStorage']);
    
    app.controller('mainCtrl', function($scope, $localStorage){
      $scope.$storage = $localStorage;
    
      $scope.$storage.entity = [];
    
      $scope.add = function(){
        $scope.$storage.entity.push('New entry');
      }
    
    });
    

    It seems that $localStorage should be passed in $scope.

    Pass $localStorage (or $sessionStorage) by reference to a hook under $scope in plain ol' JavaScript.

    Your issue may come with vm.$storage assignement.