我有一个民意调查应用程序,用户可以在其中对给定民意调查中的选项进行投票。在 html 模板中,我使用 ng-show 来显示用户已投票支持此选项或此民意调查的天气,或者是否是用户未投票的民意调查:
<div data-ng-repeat="option in poll.poll_options" class="list-group-item">
<span data-ng-if="option.option_thumb == '2'" class="glyphicon glyphicon-thumbs-up"></span>
<span data-ng-if="option.option_thumb == '1'" class="glyphicon glyphicon-thumbs-down"></span>
<div data-ng-show="optionVoted(option,authentication.user._id)">
<span data-ng-bind="option.option_text"></span>
</div>
<div data-ng-hide="optionVoted(option,authentication.user._id)">
<div data-ng-show="pollVoted(poll._id,votes)">
<a data-ng-click="updateVote()">
<span data-ng-bind="option.option_text"></span> - update
</a>
</div>
<div data-ng-hide="pollVoted(poll._id,votes)">
<a data-ng-click="createVote(poll,option,authentication.user._id,$index)">
<span data-ng-bind="option.option_text"></span> - new
</a>
</div>
</div>
<span class="option-votes"> - {{option.votes.length}}</span>
</div>
这些是上面提到的函数,用于确定选项/民意调查是否已由用户投票:
// check if option is voted
$scope.optionVoted = function(option,userId){
for (var i = 0; i < option.votes.length; i++){
if (option.votes[i].user === userId){
return true;
}
}
};
//check if poll is voted
$scope.pollVoted = function(pollId,votes){
for (var i = 0; i < votes.length; i++){
if (votes[i].poll === pollId){
return true;
}
}
}
这是创建新投票的函数:
// create a vote
$scope.createVote = function(poll,option,userId,index){
var vote = new Votes({
user:userId,
poll:poll._id,
poll_option:option._id
});
vote.poll_option_id = option._id;
vote.$save(function(vote){
option.votes.push(vote);
$scope.$apply();
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
}
前端发生的情况是,现在已投票的选项已更新(不再显示 a 标签)。我需要的是,民意调查中的其他选项也会更新,现在它们将显示 update()
而不是 create()
,而无需刷新页面。
如何获取轮询中选项的其他 html DOM 元素进行更新?
最佳答案
在 html 中,用对象属性替换 ng-show 中的函数:
例如 ng-show="option.voted"。
并在createVote函数中更新option.voted。
(使用 userId 等进行调整)
关于javascript - Angular.js 在范围更新后运行 ng-show 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27491608/