0
<input id="myid" type="number" ng-model="maxVal" ng-change="maxValCheck()"
       max="5" min="1" value="1"/>

in the controller

$scope.maxVal;
$scope.maxValCheck = function() {
    if($scope.maxVal> 5) {
        $scope.maxVal= 5;
    }
}

I want to change the value of input field to 5 when it is more than 5.But it does not work. What am I doing wrong? And is there a better way you suggest to do this?

1 Answer 1

1

Better to use directive.

Example :

<input limit-to="5" type="number"  ng-model="maxVal" >

app.directive("limitTo", [function() { return { restrict: "A", link: function(scope, elem, attrs) { var limit = parseInt(attrs.limitTo); angular.element(elem).on("keypress", function(e) { if (this.value > limit) e.preventDefault(); }); } } }]);  
Sign up to request clarification or add additional context in comments.

1 Comment

There is no need to wrap the elem argument in angular.element. It already is a jq-like argument.

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.