取消选中checkBox时,AngularJS复选框会避免计数

Ful*_*per 6 angularjs

这是我在Plunker中运行的代码

我有一个错误:当我取消选中答案时,我不想算我们选择这个答案多少次?我们只会在检查答案时计算数字.例如,我检查"是",我取消选中"是",我再次检查"是",我只会显示"是"被选中2次,而不是3次.

我读了一些关于这个问题的帖子,但是使用checked属性无法使它工作?

<input type="checkbox" ng-change="answerSelected(ans)" ng-model="checkAnswer">{{ans.answer}}
Run Code Online (Sandbox Code Playgroud)

Saj*_*ran 0

只需添加这样的检查,

  if (checkAnswer) {
      ans.count++;
      $scope.answerBoxSelected = true;
  }
Run Code Online (Sandbox Code Playgroud)

演示版

  if (checkAnswer) {
      ans.count++;
      $scope.answerBoxSelected = true;
  }
Run Code Online (Sandbox Code Playgroud)
// Code goes here

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $scope.questions = [{
      id: 1,
      question: "Do you like Foo?",
      answers: [{
        answer: "Yes",
        count: 0,
        id: 1,
        question_id: 1
      }, {
        answer: "No",
        count: 0,
        id: 2,
        question_id: 1
      }]
    },

    {
      id: 2,
      question: "Do you like Bar?",
      answers: [{
        answer: "Yes",
        count: 0,
        id: 1,
        question_id: 2
      }, {
        answer: "No",
        count: 0,
        id: 2,
        question_id: 2
      }]
    }
  ]

  $scope.question_index = 0;

  $scope.answerSelected = function(checkAnswer,ans) {
    if (checkAnswer) {
      ans.count++;
    }
     $scope.answerBoxSelected = true;
  };

  $scope.nextQuestion = function() {
    $scope.question_index++;
    $scope.answerBoxSelected = false;
  };
});
Run Code Online (Sandbox Code Playgroud)

  • 看起来这不是一个好的答案。因为如果我的答案是“我很好”,那么我们可能不会为该检查进行硬编码: if (checkAnswer.answer == 'Yes') (2认同)