Реализация сессии или хранилище localStorage CRUD для таблицы в в AngularJS
Я пытаюсь создать веб-сайт, где я могу добавлять, удалять и редактировать пользователей в таблице с помощью AngularJS. Все эти функции работают отлично.
Теперь я пытаюсь использовать localStorage или SessionStorage, чтобы предотвратить стирание данных (после редактирования, добавления или удаления пользователей) после обновления или перехода на следующую веб-страницу.
Я совсем не знаком с этими функциями. Обратите внимание, что фрагмент кода по какой-то причине не будет работать хорошо, хотя он отлично работает, когда я запускаю программу в браузере. Просто чтобы уточнить, что в моем коде вообще нет никаких ошибок. Любая помощь будет очень признательна. Заранее спасибо.
var myApp = angular.module("myApp", []); myApp.controller("myController", function ($scope) { console.log("in controller..."); $scope.newUser = {}; $scope.info = ""; $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" } ]; $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)); }; $scope.selectUser = function (user) { $scope.clickedUser = user; }; $scope.deleteUser = function () { console.log($scope.users.indexOf($scope.clickedUser)); $scope.users.splice($scope.users.indexOf($scope.clickedUser), 1); $scope.info = "User Deleted Successfully!"; }; $scope.clearInfo = function () { $scope.info = ""; }; });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>User Management- M&M</title> <link rel="icon" href="images/logo.jpg"> <link href="css/bootstrap.min.css" rel="stylesheet" /> <script type="text/javascript" src="js/angular.min.js"></script> <script type="text/javascript" src="js/app.js"></script> <!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">--> <!--<link href="CSS/Home.css" rel="stylesheet" />--> </head> <body ng-app="myApp" ng-controller="myController"> <nav class="navbar navbar-expand-lg navbar-light" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="index.html"> <img src="images/logo.jpg" alt="M&M" width="110" /> </a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="LoginPage.html">Login</a> </li> <li class="nav-item"> <a class="nav-link active js-scroll-trigger" href="User_Mgmt.html">User Management</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="CompanyManagement.html">Company Management</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="ProductPage.html">Product Management</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="ShoppingCart_Group5_Team1.html">Shopping Cart</a> </li> </ul> </div> </div> </nav> <header class="subhead"> <div class="container"> <div class="row"> <div class="col-xs-6 col-md-6"> <input class="form-control" id="ex3" type="text" placeholder="Search Users" ng-model="searchUsers"> </div> <div class="col-xs-6 col-md-6"> <button type="button" class="btn btn-info btn-lg float-right" data-toggle="modal" data-target="#myModal">Add New</button> </div> <div class="clearfix"></div> </div> <hr> <table class="table table-striped table-hover"> <thead> <tr class="table100-head"> <th>Email</th> <th>First Name</th> <th>Last Name</th> <th>Contact</th> <th>Role</th> <th>Company</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tbody> <tr ng-repeat="user in users | filter: searchUsers"> <td>{{user.email}}</td> <td>{{user.firstName}}</td> <td>{{user.lastName}}</td> <td>{{user.contact}}</td> <td>{{user.role}}</td> <td>{{user.company}}</td> <td> <button type="button" class="btn btn-info" data-toggle="modal" data-target="#myModalEdit" ng-click="selectUser(user)">Edit</button> </td> <td> <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#myModalDelete" ng-click="selectUser(user)">Delete</button> </td> </tr> </tbody> </table> </div> <!-- Pop Up-ADD NEW USER Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">New User Registration</h4> <button type="button" class="close" data-dismiss="modal">×</button> </div> <div class="modal-body"> <form class="form-horizontal" action="/action_page.php"> <div class="form-group"> <label class="control-label col-sm-2">Email</label> <div class="col-sm-10"> <input type="email" class="form-control" placeholder="Enter Email" ng-model="newUser.email"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">First Name</label> <div class="col-sm-10"> <input type="text" class="form-control" placeholder="Enter First Name" ng-model="newUser.firstName"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">Last Name</label> <div class="col-sm-10"> <input type="text" class="form-control" placeholder="Enter Last Name" ng-model="newUser.lastName"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">Contact</label> <div class="col-sm-10"> <input type="tel" class="form-control" placeholder="Enter Contact" ng-model="newUser.contact"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">Role</label> <div class="col-sm-10"> <input type="text" class="form-control" placeholder="Enter Role" ng-model="newUser.role"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">Company</label> <div class="col-sm-10"> <input type="text" class="form-control" placeholder="Enter Company" ng-model="newUser.company"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default" ng-click="saveUser()" data-dismiss="modal">Submit</button> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Pop Up-EDIT USER Modal --> <div class="modal fade" id="myModalEdit" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Edit User</h4> <button type="button" class="close" data-dismiss="modal">×</button> </div> <div class="modal-body"> <form class="form-horizontal" action="/action_page.php"> <div class="form-group"> <label class="control-label col-sm-2">Email</label> <div class="col-sm-10"> <input type="email" class="form-control" placeholder="Enter Email" ng-model="clickedUser.email"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">First Name</label> <div class="col-sm-10"> <input type="text" class="form-control" placeholder="Enter First Name" ng-model="clickedUser.firstName"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">Last Name</label> <div class="col-sm-10"> <input type="text" class="form-control" placeholder="Enter Last Name" ng-model="clickedUser.lastName"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">Contact</label> <div class="col-sm-10"> <input type="tel" class="form-control" placeholder="Enter Contact" ng-model="clickedUser.contact"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">Role</label> <div class="col-sm-10"> <input type="text" class="form-control" placeholder="Enter Role" ng-model="clickedUser.role"> </div> </div> <div class="form-group"> <label class="control-label col-sm-2">Company</label> <div class="col-sm-10"> <input type="text" class="form-control" placeholder="Enter Company" ng-model="clickedUser.company"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default" data-dismiss="modal">Submit</button> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Pop Up-DELETE USER Modal --> <div class="modal fade" id="myModalDelete" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h5 class="modal-title">Are You Sure?</h5> </div> <div class="modal-body"> <h5 style="color: red">You are going to delete the user "{{clickedUser.firstName}}"</h5> <br /> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="deleteUser()">Yes</button> <button type="button" class="btn btn-default" data-dismiss="modal">No</button> </div> </div> </div> </div> </header> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/bootstrap.min.js"></script> </body> </html>
Что я уже пробовал:
Функции CRUD работают отлично. Теперь я пытаюсь поместить локальное или сессионное хранилище так, чтобы данные(после добавления, редактирования и удаления пользователя) не стирались, когда я обновляю страницу или возвращаюсь с другой веб-страницы.
sajeetharan
в чем проблема с localstorage?