ankitdadhich ankitdadhich - 2 months ago 10
HTML Question

How to set min and max value of input control dynamically based on selection Angular

I am looking for some generic solution to update min and max value dynamically based on dropdown selection. Check this Fiddle.

If user select :


  • Hours - min and max value should be 1 to 24

  • Minutes - min and max value should be 60 to 6000

  • Seconds - min and max value should be 3000 to 10000



I am looking for some solution which will update the binding at input control based on selection. Also it should update the validation message. Looking for some generic and reusable solution so It can be reused across application.

Here is my code:
HTML

<div ng-app="app">
<div ng-controller="TimeController as vm">
<label>Desired RPO</label>
<div>
<div class="input-group">
<input type="number" class="form-control" name="desiredRPO" min="minvalue" max="maxvalue" step="1" />
<div class="input-group-btn" style="display:inline-block;">
<select class="form-control">
<option>HOURS</option>
<option>MINUTES</option>
<option>SECONDS</option>
</select>
</div>
</div>
<span>Please enter value between {{minvalue}} and {{maxvalue}}</span>
</div>
</div>


JS

var app = angular.module('app', []);
app.controller('TimeController', function($scope) {
var vm = this;
});

Answer

See answer here PLUNKER

In your HTML

<div ng-app="app">
   <div ng-controller="TimeController as vm">
   <form  name="vm.timeForm" novalidate>
      <div class="form-group">
        <label>Please select</label>
        <select class="form-control" ng-model="vm.selectedOption" ng-change="vm.updateMinMax()">
            <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 RPO</label>
        <input type="number" name="desiredRPO" class="form-control" ng-model="vm.desiredRPO" ng-min="vm.minValue" ng-max="vm.maxValue">
        <p ng-show="vm.timeForm.desiredRPO.$invalid" class="help-block">Please enter value between {{vm.minValue}} and {{vm.maxValue}}</p>
      </div>
   </form>
  </div>

In your controller

var app = angular.module('app', []);
app.controller('TimeController', function($scope) {
   var vm = this;

   vm.timeForm = {};

   vm.updateMinMax = function() {
      if(vm.selectedOption === 'hours') {
         vm.minValue = 1;
         vm.maxValue = 24;
      } else if(vm.selectedOption === 'minutes') {
         vm.minValue = 60;
         vm.maxValue = 6000;
      } else {
         vm.minValue = 3000;
         vm.maxValue = 10000;
      }
   }
});