I know that there are solutions to how to use ngstorage in our applications to have persistent data available even after refresh. I tried implementing it for the first time in my form today. But unable to figure out where I am going wrong. Can someone please let me know where I am going wrong? Also, I am looking to have the persistent functionality on adding and deleting the data.
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
};
}
]);
From my understanding, for you the issue is the value not shown in table after adding the data and refreshing the page. The problem is you are initially loading the data with static array value. The data is infact added to storage. You just have to call the initial loading from $localStorage
. Just change the self.users = [{..}]
to self.users = $localStorage.users
. I have updated the plunkr. Please take a look at it.