0

我知道有一些解决方案可以解决如何在我们的应用程序中使用 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 链接

4

1 回答 1

1

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

Plunkr

于 2017-04-03T05:59:37.157 回答