I am trying to understand why when I uncomment the lines of code below then it no longer shows my array of employees I have displaying on my index page also after I submit a form to add an employee it doesn't display it either, so yes if I keep it the way it is then it works just fine but I need it to work with the localstorage.
angular.module("MyApp").service("dataService", function() {
var employeesArray = [{employeeName:'Me', employeeStreet:'12345 Local Street', employeeCity:'MyCity', employeeState:'MyState', employeeZipCode:'12345'}];
this.getEmployees = function() {
/*
var str = localStorage.getItem("Employees");
employeesArray = JSON.parse(str) || employeesArray;
*/
return employeesArray;
}
this.addEmployee = function(employee) {
employeesArray.push(employee);
/*
var str = JSON.stringify(employeesArray);
localStorage.setItem("Employees", str);
*/
}
this.removeEmployee = function(employee) {
employeesArray.splice(employeesArray.indexOf(employee), 1);
/*
var str = JSON.stringify(employeesArray);
localStorage.setItem("Employees", str);
*/
}
});
The solution is getting the list of employees from the localStorage every time before working with it. So try to add
var employeesArray = this.getEmployees();
as the first line to addEmployee
and removeEmployee
methods. Don't forget to run localStorage.clear()
before testing new changes.
Check out please this JS fiddle: http://jsbin.com/qawabifefa/2/edit?js,output
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.