2016-10-04 50 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