Angularjs检查并比较两个输入字段值

时间:2015-12-30 15:27:46

标签: javascript angularjs

我有3个输入字段,用不同的标题(激光通道,吉格斯,设置)分隔,从JSON数组生成。这是它的样子: enter image description here

我想比较两个字段得分尝试,如果得分值大于尝试次数,则会显示错误消息。像这样:

enter image description here

但是像 The Giggsy 这样的部分有不同类型的输入字段,无需比较/检查这些字段。只有具有SCORE和ATTEMPTS的地方才能进行比较。

当部分填满时显示成功消息,如下所示: enter image description here

我能做些什么才能以有棱角的方式制作这些东西。以下是我迄今为止所做的工作: PLUNKER

HTML:

<div class="row" ng-repeat="all in options">

   <h4> {{ all.name}} </h4>
   <div class="col-sm-5ths" ng-repeat="measurement in all.measurements">
      <div class="form-group no-margin form-oneline">
        <label style="width: 100%">{{ measurement.name }}</label>
        <input ng-model="measurement.value" type="{{ measurement.type }}" min="{{ measurement.min }}" max="{{ measurement.max }}"  class="form-control display-inline" required>
        <label style="width: 100%">{{ measurement.scale }}</label>
      </div>
    </div>
    <span style="color:red;" ng-show="testDataFieldWarning(options.measurements)">
      Score can't be larger then Attempts
    </span>
    <span style="color:Green;" >
      Done!!
    </span>
  </div>
  <button type="submit" style="margin-top:50px;" ng-disable="">Submit</button>

JS

$scope.testDataFieldWarning = function (measurements) {
    var score = 0 , attempts = 0;

    angular.forEach(measurements, function(measurement) {
      if((measurement.name) == 'Score'){
        score  = measurement.value;
      }
      if((measurement.name) == 'Attempts'){
        attempts  = measurement.value;
      }
    });
    return attempts < score;
  }

   $scope.testDataFieldValidate = function (measurement) {

      var isInvalid = false;
      angular.forEach(measurement, function(v) {
        if(typeof (v.value) == 'undefined'){
          isInvalid = true;
        }
      });

      return (isInvalid);
    }

对不起英语和解释不好。

1 个答案:

答案 0 :(得分:1)

forked your plunker并添加了一些其他验证功能......

  function isScoreField(measurements) {
    if (measurements[1].name === 'Score' && measurements[2].name ==='Attempts') {
      return true;
    } else {
      return false;
    }
  }

  $scope.testDataFieldInvalid = function (measurements) {
    if (isScoreField(measurements) && parseInt(measurements[2].value) < parseInt(measurements[1].value)) {
      return true;
    } else {
      return false;
    }
  };

  $scope.testDataFieldsEntered = function (measurements) {
    if (measurements[1].value && measurements[2].value) {
      return true;
    } else {
      return false;
    }
  };

...将有条件地显示/隐藏完成/错误消息。

<span style="color:red;" ng-show="testDataFieldInvalid(all.measurements)">
  Score can't be larger than Attempts
</span>
<span style="color:Green;" ng-show="testDataFieldsEntered(all.measurements) && !testDataFieldInvalid(all.measurements)">
  Done!!
</span>

希望这有帮助!