I've encountered an issue while attempting to add a new item to my favlist. Using a for loop, I check if the item already exists in the favlist.
However, instead of adding the new item only once, it ends up being added multiple times.
What would be the most effective approach to resolve this problem?
Thank you in advance!
$scope.favlist = JSON.parse($window.localStorage.getItem("favlist"));
console.log($scope.favlist);
$scope.toggleStar = function(item) {
item.star = !item.star;
console.log(item); //object
var favlistcontent = $window.localStorage.getItem("favlist");
console.log(favlistcontent); //string
if(typeof favlistcontent !== 'string'){
$scope.favlist = [];
$window.localStorage.setItem("favlist",JSON.stringify($scope.favlist));
}
$scope.favlist = JSON.parse($window.localStorage.getItem("favlist"));
console.log($scope.favlist); //object
console.log($scope.favlist.length);
console.log(angular.equals($scope.favlist[0],item)); //true
for(i=0; i<$scope.favlist.length; i++){
if(angular.equals($scope.favlist[i],item)){
console.log("item already exists");
}
else {
$scope.favlist.push(item);
$window.localStorage.setItem("favlist",JSON.stringify($scope.favlist));
}
}