gpt4 book ai didi

javascript - 使用 ngstorage 保存持久数据

转载 作者:行者123 更新时间:2023-12-03 04:38:43 28 4
gpt4 key购买 nike

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

最佳答案

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

Plunkr

关于javascript - 使用 ngstorage 保存持久数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43176933/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com