检查输入框是否不为空并且需要切换

check if an input box is not empty and toggle required

根据第一个输入框是否为空切换必填。用户可以输入一个值,也可以清除该值。

只要用户在第一个输入框中输入一个值,所需的控件就会用红色边框突出显示。如果用户清除该值或输入框为空,则不应显示这些红色边框。

找到这个PLUNKER

如果您仅使用 Angular 属性就可以做到这一点,那就太好了。

HTML

  <div ng-controller="TimeController as vm">
    <form name="vm.timeForm" novalidate>
      <div class="form-group">
        <label>If you enter any value here below two fields becomes mandatory, 
        If I am empty below fields are not mandatory. </label>
        <input type="number" name="firstfield" class="form-control" 
        ng-model="vm.firstfield" required>
      </div>

      <div class="form-group">
        <label>Please select</label>
        <select class="form-control" ng-model="vm.selectedOption" ng-change="vm.updateMinMax()" ng-required="vm.firstfield">
          <option value="hours">HOURS</option>
          <option value="minutes">MINUTES</option>
          <option value="seconds">SECONDS</option>
        </select>
      </div>
      <div class="form-group" ng-class="{ 'has-error' : vm.timeForm.desiredRPO.$invalid && !vm.timeForm.desiredRPO.$pristine }">
        <label>Desired Time</label>
        <input type="number" name="desiredRPO" class="form-control" ng-model="vm.desiredRPO" ng-min="vm.minValue" ng-max="vm.maxValue" ng-required="vm.firstfield">
        <p ng-show="vm.timeForm.desiredRPO.$invalid" class="help-block">Please enter value between {{vm.minValue}} and {{vm.maxValue}}</p>
      </div>
    </form>
  </div>

ngRequired demo 展示了如何做到这一点。 ng-required 可以采用任何表达式,因此只需测试所需的输入即可。

<input type="text" ng-required="testCondition ()" />

查看更新的插件:https://plnkr.co/edit/7sFiBBX3wynPgcaDqisV?p=preview

简单的加ng-class if vm.textbox有值,我只是修改了index.html,看下面代码:

如果您在此处输入任何值,下面的两个字段将成为必填字段,如果我在下面的字段中为空,则不是必填字段。如果它们是强制性的,请确保用红色边框突出显示下面的控件。


    <h3>This above input control will play with our required property. </h3>

    <div class="form-group" ng-class="{'has-error': vm.firstfield && !vm.selectedOption}">
      <label>Please select</label>
      <select class="form-control" ng-model="vm.selectedOption" ng-change="vm.updateMinMax()" ng-required="vm.firstfield">
        <option value="hours">HOURS</option>
        <option value="minutes">MINUTES</option>
        <option value="seconds">SECONDS</option>
      </select>
    </div>
    <div class="form-group" ng-class="{ 'has-error' : vm.timeForm.desiredRPO.$invalid && !vm.timeForm.desiredRPO.$pristine || vm.firstfield && !vm.desiredRPO}">
      <label>Desired Time</label>
      <input type="number" name="desiredRPO" class="form-control" ng-model="vm.desiredRPO" ng-min="vm.minValue" ng-max="vm.maxValue" ng-required="vm.firstfield">
      <p ng-show="vm.timeForm.desiredRPO.$invalid && !vm.timeForm.desiredRPO.$pristine || vm.firstfield && !vm.desiredRPO" class="help-block">Please enter value between {{vm.minValue}} and {{vm.maxValue}}</p>
    </div>
  </form>
</div>

Plunker 演示:https://plnkr.co/edit/HezGVYYvhewXTJ7Irro6?p=preview