1

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);
        */
    }
});
1
  • 1
    I am guessing that the call to the service method getEmployees() is what returns the data to be shown. If you add debugging statements in this method to show what is being returned ... what is being returned? Commented Nov 9, 2014 at 21:14

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

2 Comments

Is there anything else it could be? Its not working on my system.
You can try to reproduce your problem on jsbin. Don't forget to call localStorage.clear() in the console. Pay attention on how I defined defaultEmployeesList (as string and then parsed it - so AngularJS won't throw ngRepeat:dupes error). And try to look at console (F12) and copy-paste errors here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.