Using ngstorage for persistent data - javascript

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
};
}
]);
Plnkr Link

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.
Plunkr

Related

how can you make an array save as a new object each time a function is executed and not overwrite my old array

I'm trying to make a simple register and log in system but I can only register 1 new username and password and the next time it is overwritten. I know the [2] after objpeople means it only writes on that line but what do put in to make it create a new object everytime?
var objpeople = [
{
username: "adam",
password: "coll",
email: "neilcoll#mail.com"
},
{
username: "jack",
password: "mc",
email: "jackmcgmail.com"
}
];
function register()
{
var Rusername = document.getElementById("Rname").value
var Rpassword = document.getElementById("Rpassword").value
var Remail = document.getElementById("Remail").value
var info = {};
objpeople.push(info);
objpeople[2].username=Rusername;
objpeople[2].password=Rpassword;
objpeople[2].email=Remail;
let convobjpeople = JSON.stringify(objpeople)
localStorage.people = convobjpeople
document.getElementById("logbtn").innerHTML = "Cart";
document.getElementById("logbtn").href="cart.html";
localStorage.setItem('logged', 'true');
return ;
}
edit: your code implementation
var objpeople = [
{
username: "neil",
password: "coll",
email: "neilcoll#gmail.com"
},
{
username: "jack",
password: "mc",
email: "jackmc#gmail.com"
}
];
function register()
{
let my_object = {
username: "",
password: "",
email: ""
}
var Rusername = document.getElementById("Rname").value
var Rpassword = document.getElementById("Rpassword").value
var Remail = document.getElementById("Remail").value
my_object.username=Rusername;
my_object.password=Rpassword;
my_object.email=Remail;
objpeople.push(my_object)
let convobjpeople = JSON.stringify(objpeople)
localStorage.people = convobjpeople
document.getElementById("logbtn").innerHTML = "Cart";
document.getElementById("logbtn").href="cart.html";
localStorage.setItem('logged', 'true');
return ;
}
Are you trying to create objects and push them into an array?
Just initiate an object
let my_object = {
username: "",
password: "",
email: ""
}
and when you want to assign values
var Rusername = document.getElementById("Rname").value
var Rpassword = document.getElementById("Rpassword").value
var Remail = document.getElementById("Remail").value
my_object.username=Rusername;
my_object.password=Rpassword;
my_object.email=Remail;
and finally
objpeople.push(my_object)
Edit:
It shouldn't really be behaving like this but either ways you could just create a replica object that is not passed on to a server. So for example create a objpeople2 and instead of objpeople.push(my_object) just do objpeople2.push(my_object) and then objpeople = objpeople2 and finally
let convobjpeople = JSON.stringify(objpeople). This way objpeople2 is kept as it is.

How can I pass parameter correctly?

const root = {
user: (id) => {
console.log("returning object " + JSON.stringify(id.id) + " " + JSON.stringify(storage.select("users", id.id)))
return storage.select("users", id.id)
}
}
I want to call the arrow function in root.user but I think I can't pass the parameter correctly, so I tried this --> let user = root.user('101')
and on the console I got this -->
returning object undefined
[{"firstName":"Gokhan","lastName":"Coskun","login":"gcoskun","id":101}]
{"firstName":"George","lastName":"Clooney","login":"gclooney"}
[{"firstName":"Gokhan","lastName":"Coskun","login":"gcoskun","id":101}]
I wanted the user with the id 101 get returned and got instead all of the users returned.
Why are you doing id.id but passing a string? You either pass an object with an id prop (root.user({ id: '101' })) or replace id.id with simply id.
Also, it looks like the id fields in your user objects are of type number, while you are passing a string, so depending on the logic inside storage.select you might have to change that.
Passing a number id:
// Just mocking it for the example:
const storage = {
select(key, id) {
return [
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
{ firstName: 'George', lastName: 'Clooney', login: 'gclooney' },
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
// Depending on the logic here, these types need to match.
// Using == instead of === so that it's not required here.
].filter(user => user.id == id)
},
};
const root = {
user: (id) => {
console.log(`ID = ${ id }`);
// We make sure we only return a single user or null if there isn't one:
return storage.select('users', id)[0] || null;
},
};
const user = root.user('101');
console.log(user);
Passing an object with an id prop of type number:
// Just mocking it for the example:
const storage = {
select(key, id) {
return [
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
{ firstName: 'George', lastName: 'Clooney', login: 'gclooney' },
{ firstName: 'Gokhan', lastName: 'Coskun', login: 'gcoskun', id: 101 },
// Depending on the logic here, these types need to match.
// Using == instead of === so that it's not required here.
].filter(user => user.id == id);
},
};
const root = {
user: (query) => {
console.log(`ID = ${ query.id }`);
// We make sure we only return a single user or null if there isn't one:
return storage.select('users', query.id)[0] || null;
},
};
const user = root.user({ id: '101' });
console.log(user);

For page refresh, $route.reload() or $window.location.reload() is not working in angularjs?

i am trying to refresh/reload my page after the addition of new record but its not working in my case.
Here is my Controller which calls after the save button from New Record form.
leads.save = function (isFormValid) {
leads.submitted = true;
if (isFormValid && !leads.exist) {
leadsService.addEditLeads(leads, function () {
leads.submitted = false;
$modalInstance.dismiss('cancel');
$route.reload();
});
//$window.location.reload();
}
};
Here is my Service
_addEditLeads = function (leads, callback) {
var Leads = {
id: leads.id,
title: leads.title,
is_converted: leads.is_converted,
street_address: leads.street_address,
email: leads.email,
lead_name: leads.lead_name,
first_name: leads.first_name,
middle_name: leads.middle_name,
last_name: leads.last_name,
phone_num: leads.phone_num,
postal_code: leads.postal_code,
city: leads.city,
state: leads.state,
country: leads.country,
lead_owner_id: global.User.id,
lead_source_id: leads.lead_source_id,
lead_status_id: leads.lead_status_id,
employees: leads.employees,
industry_id: leads.industry_id,
lead_date: new Date(),
account_id:leads.account_id,
};
var Accounts = {
account_name: leads.account_name,
address: leads.address,
phone: leads.phone,
website: leads.website,
description: leads.description,
employees: leads.employees,
city: leads.city,
state: leads.state,
country: leads.country,
account_owner_id: global.User.id,
industry_id: leads.industry_id
};
resource.user.addEditLead({ Lead: Leads, Accounts: Accounts })
.$promise.then(function (response) {
if (response.success) {
if (Leads.id != 0) {
//Update record
for (var i = 0; i < _leadsObject.data.length; i++) {
if (_leadsObject.data[i].id == Leads.id) {
_leadsObject.data[i] = Leads;
break;
}
}
notifyService.notifySuccess(Leads.title + " updated successfully");
}
else {
//Add new
notifyService.notifySuccess(Leads.title + " added successfully");
Leads.id = response.data;
if (_leadsObject.data != null)
_leadsObject.data.unshift(Leads);
else {
_leadsObject.data = [];
_leadsObject.data.push(Leads);
}
//callback(response.data);
}
if (typeof (callback) == 'function') {
callback();
}
}
}, _errorCallback);
};
controller add data in database through MVC and i am using sql server 2012 database.
Kindly Help me out?

Issue: Updating Elements within HTML Code Template using Angular.js

I'm having trouble updating elements using this technique.
I'm pretty new to Angular, maybe there is a better work-around?
http://codepen.io/anon/pen/qdpNxB
function ctrlSizing($scope) {
$scope.item = {
name: '',
job: '',
email: '',
mobile: '',
office: '',
};
$scope.$watch('item', function(value) {
console.debug(value);
$scope.code = document.getElementById('code_html').innerHTML();
var err = function() {
$scope.code = '' + $scope.item.name + '!';
};
};
}

my dom is not reflecting my model updated value, updationg is done by a function which is cal on button click

app.controller('thumbnailController', function ($scope) {
debugger
$scope.customers = [
{ name: 'ave Jones', city: 'Phoenix' },
{ name: 'amie Riley', city: 'Phoenix' }
];
$scope.SortCustomer = function (searchitem) {
$scope.customers = [
{ name: 'ave Jones', city: 'Phoenix' },
{ name: 'amie Riley', city: 'Phoenix' }
];
if (searchitem != 'all') {
var filter = [];
var items = $scope.customers;
// $scope.angular.forEach
var i = 0;
for (i; i < 7; i++) {
if (items[i].name[0] === searchitem) {
console.log('pushing');
filter.push(items[i]);
}
}
$scope.customers = filter; // I have update my customers list hear but it not reflecting on dom
}
};
})
with a method like that on scope you should use it with ng-click
<button ng-click="SortCustomer()">click me</button>
although here in JS instead of passing searchitem as parameter you should use model assigned to whatever input you are using
$scope.SortCustomer = function (searchitem) {
I'll be able to answer more specific as soon as you do a plunker or jsfiddle
Cheers

Categories

Resources