Search code examples
angularjshtmlangularjs-ng-model

AngularJS ng-max with expression (with DEMO of bug)


I have an input that can be either a numeric amount or percentage. I want to restrict the max amount of the input accordingly.

Is there a way I can add an ng-max to be either 100 if its percentage or nothing if it's a numeric amount?

I have tried the following, but it's not putting the max value to 100 when the input is a percentage:

<input type="number" min="0" ng-max="vm.isPercent ? '100' : ''">

Solution

  • Use the max attribute with interpolation:

        <input type="number" name="num1" ng-model="vm.num" required
               min="0" max="{{vm.isPercent ? 100 : null}}" />
    

    <script src="//unpkg.com/angular/angular.js"></script>
    <body ng-app ng-init="vm={isPercent:true, num:101}">
      <form name="form1">
        <input type="checkbox" ng-model="vm.isPercent">Is Percent<br>
        <input type="number" name="num1" ng-model="vm.num" required
               min="0" max="{{vm.isPercent ? 100 : null}}" /><br>
        Value={{vm.isPercent ? vm.num/100 : vm.num}}
      </form>
      <div ng-show="form1.$error.max" style="color: red">
         Invalid: Percentage must be less than 100
      </div>
    </body>


    DEMO of bug with ng-max:

    <script src="//unpkg.com/angular/angular.js"></script>
    <body ng-app ng-init="vm={isPercent:true, num:101}">
      <form name="form1">
        <input type="checkbox" ng-model="vm.isPercent">Is Percent<br>
        <input type="number" name="num1" ng-model="vm.num" required
               min="0" ng-max="vm.isPercent ? 100 : null" /><br>
        Value={{vm.isPercent ? vm.num/100 : vm.num}}
      </form>
      <div ng-show="form1.$error.max" style="color: red">
         Invalid: Percentage must be less than 100
      </div>
    </body>

    With the ng-max directive, if the user enters a number less than 100 and presses the up arrow, the number will increase to 100 and continue to increase.

    It does flag it as an error and prevents the form from being submitted.