【问题标题】:How to add Voting System in Angularjs with $localstorage如何使用 $localstorage 在 Angularjs 中添加投票系统
【发布时间】:2016-10-04 16:50:00
【问题描述】:

我想限制用户只为一个问题投票一次 $本地存储。

这是我的代码: 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 is not a function

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

【问题讨论】:

    标签: javascript angularjs local-storage


    【解决方案1】:

    您始终将您的 $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");
        }
    }
    

    【讨论】:

    • TypeError: $localStorage.votedQuestions.indexof 不是函数
    • 你应该在upvote函数之外的某个地方初始化你的$localStorage
    • 如何初始化?你能解释一下吗?
    • $localStorage.votedQuestions.indexOfOf 代替 of
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-21
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多