我有一个包含5个问题的表格,每个问题有3个不同的答案。

例如
q1。你最喜欢什么颜色?

单选按钮-1。值蓝色
单选按钮2。值红色
单选按钮3。灰色值

这些问题大多数都具有相同的值(蓝色,红色,灰色),这是我想要的,但是,我试图将所有值加到表格的末尾,以便我确定该人是否填写了形式等于值之一(蓝色,红色或灰色)。

我正在用angularjs构建这种形式,这就是我到目前为止所拥有的。

 <label>Q1. what is your favorite color?</label>
    <div class="form-group">
        <div class="radio">
            <label>
          <input type="radio" ng-model="formData.color" value="blue">
              blue
            </label>
        </div>
        <div class="radio">
            <label>
           <input type="radio" ng-model="formData.color" value="red">
                red
            </label>
        </div>
        <div class="radio">
            <label>
          <input type="radio" ng-model="formData.color" value="grey">
               grey
            </label>
        </div>


只有当我已经将值输入到变量中时,此代码段才有效

$scope.formData = { };
$scope.formData = [];
$scope.formData.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < $scope.formData.length; i++) {
    if ($scope.formData[i] != current) {
        if (cnt > 0) {
            console.log(current + ' shows ' + cnt + ' times');
        }
        current = $scope.formData[i];
        cnt = 1;
    } else {
        cnt++;
    }
}
if (cnt > 0) {
   console.log(current + ' shows ' + cnt + ' times');
}

最佳答案

这是示例解决方案plunker。能行吗?

控制者

  $scope.questions = [
    'Q1. what is your favorite color?',
    'Q2. what color is your car?',
    'Q3. what color best represents you?'
  ];
  $scope.formData = [];

  $scope.stats = function() {
    $scope.results = {};
    for (var i = 0; i < $scope.formData.length; i++) {
      var color = $scope.formData[i];
      if(color) {
        if ($scope.results.hasOwnProperty(color)) {
          $scope.results[color]++;
        } else {
          $scope.results[color] = 1;
        }
      }
    }
  };


模板

<div class="form-group" ng-repeat="q in questions">
  <label>{{q}}</label>
  <div class="radio">
    <label>
      <input type="radio" ng-model="formData[$index]" value="blue">blue
    </label>
  </div>
  <div class="radio">
    <label>
      <input type="radio" ng-model="formData[$index]" value="red">red
    </label>
  </div>
  <div class="radio">
    <label>
      <input type="radio" ng-model="formData[$index]" value="grey">grey
    </label>
  </div>
</div>

<button ng-click="stats()">show results</button>

<ul>
<li ng-repeat="(c, n) in results"> {{c}} shows {{n}} times</li>
</ul>

08-03 15:58