2016-10-04 51 views
0

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不是函数

,它不是存储多个问题,它只是更新对其他问题的localStorage阵列的问题ID点击

回答

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"); 
    } 
} 
+0

类型错误:$ localStorage.votedQuestions.indexof不是一个函数 – user2459458

+1

你应该某处初始化你$的localStorage了'upvote'功能 – Weedoze

+0

如何初始化?你能解释一下吗? – user2459458