gpt4 book ai didi

javascript - 如何使用 $localstorage 在 Angularjs 中添加投票系统

转载 作者:行者123 更新时间:2023-12-03 05:58:07 24 4
gpt4 key购买 nike

I want to restrict user to vote only one time for a question using $localstorage.

这是我的代码:HTML:

<ul>
<li ng-repat="question in questions"> {{question.text}}
<button ng-click="upvote(question)">Vote</button>
</li>

JS:

$scope.upvote = function(question){
var votedQuestions = [];
$localStorage.votedQuestions = votedQuestions;
if($localStorage.votedQuestions.indexof(question._id) === -1){

$localStorage.votedQuestions.push(question._id);
console.log("Thanks for Voting");
}
else {
console.log("You already voted to this question");
}

}
}

它给了我错误,比如$localStorage.votedQuestions.indexof不是一个函数

并且它不存储多个问题,它只是在其他问题点击时更新本地存储数组中的问题 ID

最佳答案

您始终将 $localStorage.votedQuestions 设置为空数组,因此用户始终可以对所有问题进行投票。

只需删除此行即可正常工作

 //APP
angular.module('myApp')
.run(['$localStorage', function($localStorage) {
$localStorage.votedQuestions = [];
}])

//Controller
$scope.upvote = function(question) {
if ($localStorage.votedQuestions.indexof(question._id) === -1) {
$localStorage.votedQuestions.push(question._id);
console.log("Thanks for Voting");
} else {
console.log("You already voted to this question");
}
}

关于javascript - 如何使用 $localstorage 在 Angularjs 中添加投票系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39846953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com