0

I have a form it includes input field which you can enter the amount of money. It has max attr. and if user entered amount of money greater than the max value I would like to set the ng-model parameter value to set max value which is the response of a RESTFull API.

Directly assigned the JSON object value to max attribute. The max value is typed in string as a response of API.

I used currency filters while assigning of the attribute values.

How to set max attribute value to ngModel object's value? If user enters the greater value than max value? Is there a way to change it immidiately and update the input field at the same time?

Also please tell me, If I'm using filters true? or NOT?

<input type="text" name="payableamount" class="form-control input-lg"
                       min="{{amount | currency:'':2}}"
                       max="{{billObj.amount | currency:'':2}}"
                       ng-model="form.bidAmount"
                       ng-required="true" ui-number-mask>
1

1 Answer 1

1

Store the value of maxAmount which you got from API and validate it inside the 'checkAmount' function

1.Using ngKeyup:

//html    
<input ng-model="amount" ng-keyup="checkAmount($event,amount)"/>

//js
function MyCtrl($scope, $log) {

    $scope.checkAmount = function(e,amt) {
      if(amt>10){ //assuming maxAmount is 10
          $scope.amount = 10;
          e.preventDefault();
        }
    };
}

2. Using Directive,

<input check-max ng-model="amount"/>


myApp.directive('checkMax', function() {
    return {
    restrict: 'AE', //attribute or element,
    require: 'ngModel',
    link:function(s,e,a,ngModel){
        e.bind('keyup',function(event){
        if(ngModel.$modelValue>10){
          event.preventDefault();
          ngModel.$setViewValue(10);
          ngModel.$render();
        }
      });
    }
  };
});

Fiddle (using ng-keyup) : http://jsfiddle.net/r74a5m25/202/

Fiddle (using directive) : http://jsfiddle.net/r74a5m25/203/

Sign up to request clarification or add additional context in comments.

6 Comments

what if we create an directive for that?
Yes you could do that in case you need the same logic in many places.
Added the solution using directive ;)
Thank you @GopinathShiva that works for me. I was curious about string value but you can change it to amt > '10' also works. Thanks!
Cool. Comparing numbers in a 'string' datatype though works is not a good practise. Convert them into numbers using parseInt or with '+' operator. Happy coding :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.