AngularJS中的会话或LocalStorage CRUD表

时间:2018-11-09 18:03:38

标签: javascript html angularjs

我正在使用angularjs和localstorage创建一个CRUD网页。添加,编辑和删除功能都可以很好地工作。添加或删除用户后,我能够使用localstorage并保存数据。

但是我无法保存有关本地存储的已编辑用户详细信息。它们会在刷新网页时被擦除。 $ scope.selectUser 是我用来编辑用户的功能。预先感谢。

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 = "";
    };
});

0 个答案:

没有答案