【问题标题】:Value in table is not getting updated after updating $localStorage data in AngularJS更新 AngularJS 中的 $localStorage 数据后,表中的值未更新
【发布时间】:2017-09-21 10:06:57
【问题描述】:

我在 AngularJS 中有两个组件。一个组件usersList 包含一个表格

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

在页面加载时,此组件从 API 获取用户列表及其详细信息并将其存储在 $localStorage 中。 其他是表单editUserProfile,其中的值被编辑和删除

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
  }
})

所以基本上,我通过调用 API 来编辑用户详细信息和删除用户,当成功编辑/删除时,我会刷新 usersList 的 $localStorage 值,它是一个 JSON 对象。

在更新数据之前一切正常,但是更改不会反映在 usersList 组件中。我这样做是为了保存对 API 的调用,以便仅显示数据。欢迎任何其他想法。

【问题讨论】:

  • 什么是 $storage 和 $localstorage ?
  • 我正在使用 ngStorage。 $storage 和 $localStorage 与 ngStorage 相关。
  • 别忘了提一下 :)

标签: javascript angularjs html local-storage ng-storage


【解决方案1】:

看到这个Plunkr工作。

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');
  }

});

看来$localStorage应该传入$scope

在普通的 JavaScript 中通过引用 $scope 下的钩子来传递 $localStorage(或 $sessionStorage)。

您的问题可能与vm.$storage 分配有关。

【讨论】:

  • 这行得通!但是我通过在 ngStorage 值上使用 $watch 克服了这个问题,即 usersList
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-08
  • 2017-01-02
  • 2018-03-17
  • 1970-01-01
  • 1970-01-01
  • 2015-10-21
  • 1970-01-01
相关资源
最近更新 更多