I am currently facing a challenge with my Javascript code for a simple web application that involves AngularJS. Here is the snippet of code I am working on:
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";
}
};
I have set up the above code and it works fine on the frontend where users can add and delete items from the list. However, I am looking for a solution to ensure that any changes made by the user are persisted even after reloading the page. Does anyone have suggestions on how to achieve this? Would storing data in cookies be a viable option, and if so, how can it be implemented?
Thanks!
UPDATE: I made some modifications to the script but it still doesn't seem to work as intended.
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 {
getItems: function () {
var itemsStr = _sessionStorage.getItem(storageKey);
if (itemsStr) {
return angular.fromJson(itemsStr);
}
},
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;
};
}];
Any suggestions on how to fix this issue and ensure that if a user has no items, it defaults to $scope.items = ["name 1", "name 2", "name 3"]; ?