User528491 User528491 - 3 months ago 9
AngularJS Question

AngularJS: Conditionally set min based on other field

I have two input fields: A

select
with
Yes/No
and a
number
input.
When the
select
is No, the
number
is disabled and set it to 0. But when the
select
is Yes, I would like to set it to a minimum of 1.

<body ng-app="KnobDemoApp">
<div ng-controller="knobCtrl as knob">
<label>Yes/No:</label>
<select ng-model="knob.yesno" name="yesnoName" ng-options="x for x in yes_no">
<option value="" disabled>Select One</option>
</select>
<br>
<label>Number:</label>
<input type="number" ng-model="numyesno" name="numName"
ng-disabled="knob.yesno != 'Yes'"
min="if knob.yesno == 'Yes' then 1 else 0"></input>
<br><br>
<span> Value: </span>{{knob.yesno}} <br>
<span> Check: </span>{{knob.yesno != 'Yes'}}
</div>
</body>
<script>
var app = angular.module('KnobDemoApp', [])
app.controller('knobCtrl', function ($scope) {
$scope.yes_no = ["Yes", "No"];
});
</script>

Answer

You can use ngChange to get the current value of your ngModel, then you can set your input to 0 when it's equivalent to "No".

angular
  .module('KnobDemoApp', [])
  .controller('knobCtrl', function($scope) {
    $scope.setValue = setValue;
    $scope.yes_no = ["Yes", "No"];

    function setValue() {
      if ($scope.knob.yesno === 'No') {
        $scope.numyesno = 0;
      } else {
        $scope.numyesno = 1
      }
    }
  });
<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body ng-app="KnobDemoApp">
  <div ng-controller="knobCtrl as knob">
    <label>Yes/No:</label>
    <select ng-model="knob.yesno"
            name="yesnoName"
            ng-options="x for x in yes_no"
            ng-change="setValue()">
      <option value hidden>Select One</option>
    </select>
    <br>
    <label>Number:</label>
    <input type="number"
           ng-model="numyesno"
           name="numName"
           ng-disabled="knob.yesno !== 'Yes'"
           min="{{knob.yesno === 'Yes' ? 1 : ''}}">
    <br>
    <br>
    <span> Value: </span>{{knob.yesno}}
    <br>
    <span> Check: </span>{{knob.yesno != 'Yes'}}
  </div>
</body>

</html>