使用 ngstorage 存储持久数据

Using ngstorage for persistent data

我知道有一些解决方案可以解决如何在我们的应用程序中使用 ngstorage,即使在刷新后也可以使用持久数据。我今天第一次尝试在我的表单中实现它。但无法弄清楚我要去哪里错了。有人可以让我知道我哪里出错了吗?此外,我希望在添加和删除数据时具有持久的功能。

angular.module('myApp', ['ngStorage'])
  .controller('AppController', ['$scope', '$localStorage',
    '$sessionStorage',
    function($scope,$localStorage,$sessionStorage) {
      var self = this;

      self.$storage = $localStorage;

      self.user = {
        id: null,
        username: '',
        address: '',
        email: ''
      };
      self.id = 4;

      self.users = [{
        id: 1,
        email: 'sam@tarly.com',
        firstname: 'Sam',
        lastname: 'Tarly',
        telephone: 1234567890,
        address: 'NY',

      }, {
        id: 2,
        email: 'jon@snow.com',
        firstname: 'Jon',
        lastname: 'Snow',
        telephone: 9876543210,
        address: 'The Wall',
      }, {
        id: 3,
        email: 'dany@targaryen.com',
        firstname: 'Dany',
        lastname: 'Targaryen',
        telephone: 1234987650,
        address: 'NEBRASKA'
      }];

      self.submit = function() {
        if (self.user.id === null) {
          self.user.id = self.id++;
          alert('Added New User', self.user);
          self.users.push(self.user); 
          $localStorage.users = self.users;
        } else {
          for (var i = 0; i < self.users.length; i++) {
            if (self.users[i].id === self.user.id) {
              self.users[i] = self.user;
              break;
            }
          }
          alert('User updated with id ', self.user.id);
        }
        self.reset();
      };

      self.edit = function(id) {
        alert('id to be edited', id);
        for (var i = 0; i < self.users.length; i++) {
          if (self.users[i].id === id) {
            self.user = angular.copy(self.users[i]);
            break;
          }
        }
      };

      self.remove = function(id) {
        alert('id to be deleted', id);
        for (var i = 0; i < self.users.length; i++) {
          if (self.users[i].id === id) {
            self.users.splice(i, 1);
            $localStorage.users = self.users;
            if (self.user.id === id) { //It is shown in form, reset it.
              self.reset();
            }
            break;
          }
        }
      };

      self.reset = function() {
        self.user = {
          id: null,
          username: '',
          address: '',
          email: ''
        };
        $scope.myForm.$setPristine(); //reset Form
      };

    }
    ]);

Plnkr Link

据我了解,您的问题是添加数据并刷新页面后 table 中未显示的值。问题是您最初是使用静态数组值加载数据。数据实际上已添加到存储中。您只需从 $localStorage 调用初始加载。只需将 self.users = [{..}] 更改为 self.users = $localStorage.users。我已经更新了plunkr。请看一下。

Plunkr