繁体   English   中英

AngularJS:检查单选按钮的值

[英]AngularJS: Checking the value of the radio button

我已经使用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"
]

变量$parent.selopt包含选定的值(父范围的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对其进行验证。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM