JS投票系统{{绑定}}在点击时给出空值

JS vote system {{bindings}} gives null on click?

本文关键字:空值 系统 绑定 JS      更新时间:2023-09-26

该错误未显示在开发人员工具中,因此我想这可能与数据本身及其读取方式有关。{{upVote}} 和 {{downVote}} 都以没有值开头,并在单击时显示 null。不知何故,按钮都链接了?我正在为每个项目设置每票。

背景投票系统,具有单独的上下分数(不作为单一投票分数净额)。希望分数保留在数据库中。

我没有考虑过限制每个用户的投票,但如果您有想法,请随时包含在您的回复中。谢谢!

该 JS 文件

  $scope.upVote = function () {
    if ($scope.voteType == "down") {
        $scope.upVote++;
    }
    $scope.upVote++;
    $scope.voteType = "up";
  };
  $scope.downVote = function () {
    if ($scope.voteType == "up") {
        $scope.downVote++;
    }
    $scope.downVote++;
    $scope.voteType = "down";
  };


帖子在 scope.post 美元中保存为:

  $scope.post = {               
    title:      '',
    upVote: 0,
    downVote: 0
  };


该按钮在 html 中如下所示:

  <i ng-click="downVote()" 
    class="fa fa-chevron-circle-down fa-2x"  
    ng-class="{true:'downVote', false:''}[vote=='downVote']"></i>
$scope

控制器范围内是相同的。它在upVote内不会改变。

angular.module('starter').controller('PostCtrl', function($scope, Post) {
  $scope.posts = Post.all;
  $scope.upVote = function () {
    $scope.upVote++; // NOT the upVote property of the clicked post
    ...
  };
});

你会想从这样的$scope.posts中获取帖子:

angular.module('starter').controller('PostCtrl', function($scope, Post) {
  $scope.posts = Post.all;
  $scope.upVote = function (post) {
    post.upVote++;
    ...
  };
});

在 ng 重复中传递post

<div class="row" ng-repeat="(postId, post) in posts">
  <i ng-click="upVote(post)" ...></i>
  ...
</div>

这样,您将引用点击的帖子,而不是$scope本身的属性。