Session or LocalStorage CRUD table in AngularJS - javascript

I am creating a CRUD webpage using angularjs and localstorage. The add, edit and delete functions all work perfectly well. I was able to use localstorage and save data after adding or deleting a user.
But i am unable to save edited user details on localstorage. They get erased on refresh of the webpage. The $scope.selectUser is the function I use to edit a user. Thanks in advance.
var myApp = angular.module("myApp", []);
myApp.controller("myController", function ($scope) {
console.log("in controller...");
$scope.newUser = {};
$scope.info = "";
if (localStorage.getItem("users") === null) {
$scope.users = [
{ email: "John#yahoo.com", firstName: "John", lastName: "Doe", contact: "281-283-2480", role: "Supplier-Admin", company: "Apple" },
{ email: "Rick#yahoo.com", firstName: "Rick", lastName: "Fraiser", contact: "987-283-2489", role: "Supplier-User", company: "Apple" },
{ email: "Sam#yahoo.com", firstName: "Sam", lastName: "Tarly", contact: "456-786-2480", role: "BuyerAdmin", company: "Samsung" }
];
localStorage.setItem("users", JSON.stringify($scope.users));
} else {
$scope.users = JSON.parse(localStorage.getItem("users"));
}
$scope.saveUser = function () {
console.log("Saving...");
$scope.users.push($scope.newUser);
$scope.info = "New User Added Successfully!";
$scope.newUser = {};
localStorage.setItem("users", JSON.stringify($scope.users));
//localStorage.setItem("email", $scope.users);
};
$scope.selectUser = function (user) {
$scope.clickedUser = user;
localStorage.setItem("users", JSON.stringify($scope.users));
};
$scope.deleteUser = function () {
console.log($scope.users.indexOf($scope.clickedUser));
$scope.users.splice($scope.users.indexOf($scope.clickedUser), 1);
localStorage.setItem("users", JSON.stringify($scope.users));
$scope.info = "User Deleted Successfully!";
};
$scope.clearInfo = function () {
$scope.info = "";
};
});

Related

Javascript Can't catch an error inside map function

let's say I have a usersList like this:
var usersList = [
{ firstName : 'Adam', lastName: 'Yousif', age: 23 },
{ firstName : 'Mohamed', lastName: 'Ali' },
{ firstName : 'Mona', lastName: 'Ahmed', age: 19 },
];
Now I want to call map function on usersList and return a modified list like so :
var returnList = usersList.map((_user) => {
var _age;
try {
_age = _user.age;
} catch (error) {
console.log('I caught error here : ', error); // <-- not printed
_age = 'FAILSAFE-VAULE'; // <-- not set
}
var obj = {
firstName: _user.firstName,
lastName: _user.lastName,
age: _age
}
return obj;
});
I have a try-catch block inside the map function, the purpose if it is to replace the undefined property "age" of the second user with a 'FAILSAFE-VALUE'. but it doesn't work as should.
console.log(returnList);
// prints
// [
// { firstName: 'Adam', lastName: 'Yousif', age: 23 },
// { firstName: 'Mohamed', lastName: 'Ali', age: undefined }, <-- not what I want
// { firstName: 'Mona', lastName: 'Ahmed', age: 19 }
// ]
How to catch an error inside javascript map function?
Thank you
You don't need to do try catch for that:
usersList.map((_user) => {
return {
firstName: _user.firstName,
lastName: _user.lastName,
age: _user.age || 'FAILSAFE-VAULE'
};
});
That's because nothing is thrown (the age is just undefined). If you want information about this "error" during the map-operation, the first part of the snippet may be an idea. If you really want to use try - catch, use the second part (it throws 'manually' when _user.age is undefined). The latter demonstrates (by the way) that try - catch does work within a map-operation.
const usersList = [{
firstName: 'Adam',
lastName: 'Yousif',
age: 23
},
{
firstName: 'Mohamed',
lastName: 'Ali'
},
{
firstName: 'Mona',
lastName: 'Ahmed',
age: 19
},
];
const getFailSafe = user => {
if (!user.age) {
console.log(`Note: user.age not available for ${user.firstName} ${user.lastName}`);
return `FAILSAFE-VAULE`;
}
return user.age;
};
// 1. use a warning if .age not present
const returnList = usersList
.map((_user) => ({
firstName: _user.firstName,
lastName: _user.lastName,
age: getFailSafe(_user)
})
);
// 2. throw an Error if .age not present
const returnListWithError = usersList
.map((_user) => {
let retVal = {
firstName: _user.firstName,
lastName: _user.lastName,
}
try {
retVal.age = _user.age ||
(() => {
throw new Error(`ERROR: user.age not available for ${
_user.firstName} ${_user.lastName} (will continue with 'FAILSAFE-VAULE')`);
})();
} catch (err) {
console.log(`${err.message}`);
retVal.age = `FAILSAFE-VAULE`;
}
return retVal;
});
console.log(returnList.find(v => isNaN(v.age)));
console.log(returnListWithError.find(v => isNaN(v.age)));
.as-console-wrapper { top: 0; max-height: 100% !important; }
try...catch block would not work there as after accessing a value which does not exist you just receive an undefined
just do it next way:
var returnList = usersList.map((_user) => {
return {
firstName: _user.firstName,
lastName: _user.lastName,
age: _user.age ? _user.age : 'FAILSAFE-VAULE'
}
});

IndexedDB cursor does not get next record after update on iOS

I have attempted to research similar cases, but nothing has matched what I am experiencing. Consider the following:
var req = indexedDB.open("myDatabase", 1);
req.onupgradeneeded = function (evt) {
var objStore = evt.target.result.createObjectStore("customers", { keyPath: "ID", autoIncrement: true });
objStore.createIndex("fName", "fName", { unique: false });
objStore.createIndex("lName", "lName", { unique: false });
objStore.createIndex("country", "country", { unique: false });
var obj1 = { fName: "James", lName: "Smith", age: 25, country: "United States", reviewStatus: "pending" };
var obj2 = { fName: "Tim", lName: "Jones", age: 32, country: "Canada", reviewStatus: "pending"};
var obj3 = { fName: "James", lName: "Miller", age: 22, country: "United States", reviewStatus: "pending"};
var obj4 = { fName: "James", lName: "Thompson", age: 40, country: "United Kingdom", reviewStatus: "pending"};
var obj5 = { fName: "Joseph", lName: "Harris", age: 28, country: "Canada", reviewStatus: "pending"};
var obj6 = { fName: "James", lName: "Jackson", age: 30, country: "United States", reviewStatus: "pending"};
objStore.add(obj1);
objStore.add(obj2);
objStore.add(obj3);
objStore.add(obj4);
objStore.add(obj5);
objStore.add(obj6);
};
req.onsuccess = function (evt) {
var tx = this.result.transaction("customers", "readwrite");
var objStore = tx.objectStore("customers");
var index = objStore.index("fName");
var cnt = index.count(IDBKeyRange.only("James"));
cnt.onsuccess = function () {
console.log(cnt.result + " records with fName: James");
};
var cursor = index.openCursor(IDBKeyRange.only("James"));
cursor.onsuccess = function (e) {
var record = e.target.result;
if (record) {
var updateData = record.value;
updateData.reviewStatus = "reviewed";
//update some other fields
var updateReq = record.update(updateData);
console.log("updating record");
record.continue();
}
};
cursor.onerror = function () {
console.log("error using cursor");
};
tx.oncomplete = function () {
console.log("got to transaction oncomplete");
//do other work required once cursor updates done
};
tx.onerror = function () {
console.log("error in transaction");
};
};
req.onerror = function () {
console.log("error opening database");
};
My database has 4 records with fName = "James". I used Chrome (v71) to first test this and get the results:
4 records with fName: James updating record updating
record updating record updating record got to
transaction oncomplete
Subsequent tests on Firefox (v64), Opera (v56), and Chrome for Android and all produced these expected results. When I test on iOS (11.4), I get the results:
4 records with fName: James updating record got to
transaction oncomplete
I don't get any console errors or any of the messages in my onerror functions. I cannot figure out why in iOS only the the first record is updated and the cursor doesn't move on to the other records. Is there an error in my code that I am unaware of or is this some kind of bug in iOS?
Looks like it is a bug in Safari. I submitted a bug report here https://bugs.webkit.org/show_bug.cgi?id=192987 - hopefully they will fix it in the near future!

JavaScript build a dynamic object

I have a var named onversation that contains this:
{
"conversationId": "adbabc54-3308-436d-a48b-932f4010d3c6",
"participantId": "415651e6-f0a5-4203-8019-4f88c3ed9cd5"
}
I also have an object named person that contains this:
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
What I'd like is to have a combined object called result that looks like this
result {
conversation {
conversationId : adbabc54-3308-436d-a48b-932f4010d3c6,
participantId : 415651e6-f0a5-4203-8019-4f88c3ed9cd5
},
person {
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
}
How would I do this dynamically whereby the result object is built using the name of the var 'conversation' and name of the object 'person' ?
Also, the length of either conversation or person can be any length.
Pure JavaScript if possible , but could use underscore etc.
Try it
var result = {
'conversation': conversation,
'person': person
}
Dynamic
var result = {}
result['person'] = person
or
resilt.person = person
If I understand your question correctly, you can use object shorthand notation which is supported in most browsers (Probably all of them, except IE11) for simplifying your solution even more:
var conversation =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var person =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = { conversation, person }
console.log(result)
EDIT:
If only the variable name changes, and it's properties names stay the same or have some sort of unique key, you can use a for loop on the object's keys.
For example:
var someConversationVariableName =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var somePersonVariableName =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = { someConversationVariableName, somePersonVariableName }
for (key in result) {
if(result[key]['conversationId']) {
console.log(`Found conversation object. It's name is: ${key}`);
}
else if(result[key]['firstname']) {
console.log(`Found person object. It's name is: ${key}`);
}
}
If you need to defer adding objects, you can also take this approach:
var conversation =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var person =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = {};
result['conversation'] = conversation;
result['person'] = person;
console.log(result);
This Must work :-
var conversation =
{
"conversationId": "adbabc54-3308-436d-a48b-932f4010d3c6",
"participantId": "415651e6-f0a5-4203-8019-4f88c3ed9cd5"
}
var person=
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
var result = {
'conversation': conversation,
'person': person
}

A program in javascript using constructors

<script>
<!-- A program to search for a friend from an object -->
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "205-555-1111",
address:["One Microsoft Day","Redmond","WA","90852"]
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "408-555-2222",
address: ["One Infinite Loop", "Cupertino", "CA", "95014"]
},
wendy: {
firstName: "Wendy",
lastName: "Johnson",
number: "510-555-3333",
address: ["3555 Anyplace drive","New York", "NY","11001"]
}
}
alert(friends["steve"].lastName);
alert(friends.length);
var search = function(name)
{
document.write(name);
for (var nameSearch in friends)
{
alert(nameSearch.firstName);
if(friends[nameSearch].firstName===name)
{
return friends[nameSearch];
}
}
}
search("Wendy");
</script>
Theres a couple things wrong with your code:
Objects do not have a length property so the second alert for friends.length will not work
When you're using for in you are referencing the key of the object, so in this case it will be bill, steve, or wendy so when you do nameSearch.firstName it will be undefined since nameSearch is a string
Finally, the reason that your example is failing is because you're searching against case-sensitive text. wendy != Wendy. Also please keep in mind that triple equals checks the constructor.
To fix your code, you can try just lower-casing all of your search text:
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "205-555-1111",
address:["One Microsoft Day","Redmond","WA","90852"]
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "408-555-2222",
address: ["One Infinite Loop", "Cupertino", "CA", "95014"]
},
wendy: {
firstName: "Wendy",
lastName: "Johnson",
number: "510-555-3333",
address: ["3555 Anyplace drive","New York", "NY","11001"]
}
};
var search = function(name) {
for (var nameSearch in friends) {
if(friends[nameSearch].firstName.toLowerCase()===name.toLowerCase()) {
return friends[nameSearch];
}
}
}
console.log(search("wendy"));

AngularJS: Call JSON array value in nested Controller

How to call Json array value in other controller. Basically i work with nested controller. Nested controller will return first character of firstname and lastname.
For example if my first name is Anand Jee then It will return AJ, Rohan Kumar then it will return RK.
My AngularJS code.
//create module
var myApp = angular.module("myApp", []);
//create controller
myApp.controller("empCtrl", function ($scope) {
var Employees = [
{ FirstName: "Anand", LastName: "Jee", Roles: "Web Developer", Technology: ".NET" },
{ FirstName: "Pritus", LastName: "Dubey", Roles: "Window App Developer", Technology: "XAMARIN" },
{ FirstName: "Vineet", LastName: "Rai", Roles: "Web Developer", Technology: ".NET" },
{ FirstName: "Nilesh", LastName: "Pathak", Roles: "UI/UX Developer", Technology: "Photoshop" },
{ FirstName: "Vikesh", LastName: "Juyal", Roles: "Web Developer", Technology: "PHP" }
];
$scope.Employees = Employees;
});
myApp.controller("EmpShortName", function ($scope) {
$scope.getEmpShortName = function () {
//$scope.empShortName = $scope.Employees.FirstName + " " + $scope.Employees.LastName;//here is problem
$scope.empShortName = "NP";//For temp declaration
return $scope.empShortName;
};
});
PLUNKER DEMO
Pass the Employee object into the getEmpShortName function. Then just return the parsed value. Also, no need for the EmpShortName controller, just put the scope function in your empCtrl controller:
HTML:
<div class="empTextImage">{{getEmpShortName(emp)}}</div>
JS:
$scope.getEmpShortName = function (emp) {
return emp.FirstName.substr(0,1) + emp.LastName.substr(0,1);
};
Updated Plunker

Categories

Resources