【发布时间】:2019-11-20 23:38:52
【问题描述】:
我正在努力处理我目前正在研究的一些 Javascript。所以我有一个简单的网络应用程序,下面是 AngularJS 的东西:
app.filter('startFrom', function () {
return function (input, start) {
if (input) {
start = +start;
return input.slice(start);
}
return [];
};
});
app.controller('MainCtrl', ['$scope', 'filterFilter', function ($scope, filterFilter) {
$scope.items = ["name 1", "name 2", "name 3"
];
$scope.addLink = function () {
$scope.errortext = "";
if (!$scope.newItem) {return;}
if ($scope.items.indexOf($scope.newItem) == -1) {
$scope.items.push($scope.newItem);
$scope.errortext = "submitted";
} else {
$scope.errortext = " in list";
}
};
所以我有这些,我有一个显示项目列表的 html 端。用户可以选择从项目数组中添加和删除这些项目。 问题。如何确保当用户从数组中添加或删除项目时,重新加载页面后仍然可以看到编辑后的列表?有人可以建议一种处理方法吗?是否可以存储在 cookie 中,并在每次添加/删除操作后更新它们,如果可以,如何?
谢谢
更新: 所以我更改了脚本,但它似乎仍然无法正常工作。
var app = angular.module('App', ['ui.bootstrap']);
app.filter('startFrom', function () {
return function (input, start) {
if (input) {
start = +start;
return input.slice(start);
}
return [];
};
});
app.factory('ItemsService', ['$window', function ($window) {
var storageKey = 'items',
_sessionStorage = $window.sessionStorage;
return {
// Returns stored items array if available or return undefined
getItems: function () {
var itemsStr = _sessionStorage.getItem(storageKey);
if (itemsStr) {
return angular.fromJson(itemsStr);
}
},
// Adds the given item to the stored array and persists the array to sessionStorage
putItem: function (item) {
var itemsStr = _sessionStorage.getItem(storageKey),
items = [];
if (itemStr) {
items = angular.fromJson(itemsStr);
}
items.push(item);
_sessionStorage.setItem(storageKey, angular.toJson(items));
}
}
}]);
app.controller('MainCtrl', ['$scope', 'filterFilter', 'ItemsService', function ($scope, filterFilter, ItemsService) {
$scope.items = ItemsService.get($scope.items)
$scope.addLink = function () {
$scope.errortext = "";
if (!$scope.newItem) {
return;
}
if ($scope.items.indexOf($scope.newItem) == -1) {
$scope.items.push($scope.newItem);
$scope.errortext = "Submitted";
$scope.items = ItemsService.put($scope.items)
} else {
$scope.errortext = "Link in the list";
}
};
$scope.removeItem = function (item) {
$scope.items.splice($scope.items.indexOf(item), 1);
$scope.items = ItemsService.put($scope.items)
$scope.resetFilters;
};
}]);
任何帮助如何修复它以及如何确保如果用户没有任何项目,它将使用默认 $scope.items = ["name 1", "name 2", "name 3" ]; ?
【问题讨论】:
-
有一个 Angular 的 cookie 服务 $cookie。您可以随时添加/编辑它们。
-
不只是cookies,从sessionStorage存储和检索是对的。
标签: javascript angularjs cookies