在控制器中使用ng-select和if else语句

时间:2016-03-21 09:48:00

标签: javascript angularjs

我试图将值从简单的ng-select传递给控制器​​,然后使用if语句检查所选值是否等于我需要的值,如下所示:

HTML

<form role="form">
  <div class="form-group">
    <label for="selectAnswerPhaseOneQuestionOne">Select answer:</label>
    <select class="form-control" id="selectAnswerPhaseOneQuestionOne"
    data-ng-model="questionOneAnswer" data-ng-dropdown required
    name="type">
      <option></option>
      <option value="True">True</option>
      <option value="False">False</option>
    </select>
  </div>
</form>

<button data-ng-click="submitPhaseOneAnswers()"
class="btn btn-primary" type="submit">

JS

$scope.questionOneAnswer = '';

$scope.submitPhaseOneAnswers = function () {
  var score = 0;
  if($scope.questionOneAnswer == 'True') {
    score = score + 10;
    alert('Your score is now ' + score);
  }
}

简单来说,上面的方法并不起作用,按钮点击只是绕过了if语句。最后,我上面列出的代码实际上包含了我在HTML中的4个选择组,在按下按钮时我需要评估它们是否是真的&#39; True&#39;或者&#39;错误。

2 个答案:

答案 0 :(得分:0)

您可以逐步检查您的代码。

  1. 检查HTML文件中的控制器名称和JS文件(具有相同名称)

  2. 将console.log()放在函数$ scope.submitPhaseOneAnswers()中,以检查单击按钮时是否正在运行。

  3. 如果功能正常,可能$ scope.questionOneAnswer =''会导致错误。

答案 1 :(得分:0)

使用ng-options

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

app.controller("myCtrl", function ($scope) {
  $scope.options = ['True', 'False'];

  $scope.submitPhaseOneAnswers = function () {
    var score = 0;
    
    if($scope.questionOneAnswer == 'True') {
      score += 10;
    }
    
    alert('Your score is now ' + score);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>

<form role="form" ng-app="myApp">
  <div class="form-group" ng-controller="myCtrl">
    <label for="selectAnswerPhaseOneQuestionOne">Select answer:</label>
    <select class="form-control" id="selectAnswerPhaseOneQuestionOne"
    ng-model="questionOneAnswer" name="type" ng-options="option as option for option in options"></select>
    <button ng-click="submitPhaseOneAnswers()" class="btn btn-primary">Submit</button>
  </div>
</form>