角度.js在范围更新后运行 ng-show 函数

Angular.js run ng-show function after scope is updated

本文关键字:运行 ng-show 函数 更新 js 范围 角度      更新时间:2023-09-26

我有一个投票应用程序,用户可以在其中为给定民意调查中的选项投票。 在 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标签)。 我需要的是,民意调查中的其他选项也会更新,现在它们不会create()而是显示update(),而无需刷新页面。

如何更新轮询中选项的其他 HTML DOM 元素?

在 html 中,将 ng-show 中的函数替换为对象属性:

例如,ng-show="option.voted"。

并更新选项.vote在创建投票功能中。

(使用用户ID等进行调整)

确保将新投票推送到作用域中的正确对象上。看起来您正在视图中显示来自$scope.poll.poll_options的数据,但您正在createVote函数中添加options.votes