AngularJS:检查单选按钮的值

时间:2016-01-19 15:32:56

标签: javascript angularjs json

我一直在使用AngularJS一段时间了。我有一个单选按钮,为用户提供具有正确答案值的选项和json数据。我如何进行比较?

代码:

var testControllers = angular.module('testControllers', []);

testControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
  $http.get('js/data.json').success(function(data) {
    $scope.questions = data;
    $scope.artistOrder = 'name';
  });
}]);

testControllers.controller('DetailsController', ['$scope', '$http','$routeParams' ,function($scope, $http, $routeParams) {
  $http.get('js/data.json').success(function(data) {
    $scope.questions = data;
    $scope.whichItem = $routeParams.itemId;
    $scope.parseInt = parseInt;
    if($routeParams.itemId > 0){
        $scope.prevItem = Number($routeParams.itemId) - 1;
    }
    else{
        $scope.prevItem = $scope.questions.length - 1;
    }


    if($routeParams.itemId < $scope.questions.length-1){
        $scope.nextItem = Number($routeParams.itemId) + 1;
    }
    else{
        $scope.nextItem = 0;
    }
  });
}]);

HTML:

<link rel="stylesheet" href="css/common.css" />
<section class="artistinfo">
    <div class="mcq" ng-model: "questions">
      <center><a href = "#details/{{prevItem}}" class = "button">PREV</a>
      <a href = "#details/{{nextItem}}" class = "button">NEXT</a></center>
      <div class = "qanda">
        <h3 class = "qnum">QUESTION {{parseInt(whichItem)+1}}</h3>
        <p class = "ques" math-jax-bind = "questions[whichItem].ques"></p>    
        <ul>
              <li class= "optlist" ng-repeat="item in questions[whichItem].opts">
              <label class="formgroup">
              <input type="radio" name = "q" ng-model = "$parent.selopt" value = "{{item.pos}}"><span math-jax-bind = "item.val"></span>
             </label>
             </li>
        </ul>
      </div>
      <center><a href = "#list" class = "button">List View</a></center>
      <p>{{selopt}}</p>
    </div>  
</section>

这是我拥有的JSON数据:

"opts":[  
    {  
      "pos":"A",
      "val":"3"
    },
    {  
      "pos":"B",
      "val":"6"
    },
    {  
      "pos":"C",
      "val":"9"
    },
    {  
      "pos":"D",
      "val":"0"
    }
    "answer":"B"
]

1 个答案:

答案 0 :(得分:0)

变量$parent.selopt包含所选值(父范围&#39; s selopt)。

如果您需要说明:当您选择一个值时,通过单击单选按钮,您在指令的ng-model属性中指定的变量

<input type="radio" name = "q" ng-model = "$parent.selopt" value = "{{item.pos}}">

将使用所选值进行更新。

如果您想将其与opts.answer进行比较,您只需执行以下操作:

 $scope.questions.answer == $parent.selopt

请注意,您的JSON无效。

应该是:

[{
    "pos": "A",
    "val": "3"
}, {
    "pos": "B",
    "val": "6"
}, {
    "pos": "C",
    "val": "9"
}, {
    "pos": "D",
    "val": "0"
}, {
    "answer": "B"
}]

您始终可以使用JSON Lint对其进行验证。