简体   繁体   中英

For ng-keyup unable to do event.preventDefault() and ng-keypress lagging behind a value for input type number in angular.js

Problem: Input type number with min, max is not working while typing in input box we can type less/more than min, max value. (but by the arrow of input type number it is working fine.)

Requirement: restrict to enter the value in input type number that not in range of min and max

"Using Angular.js want to solve this problem without an extra directive and without changing the input type number to text." Plunker

ng-keyup: unable to do event.preventDefault() why? This is why we can type more/less than min or max value. I am getting the correct value while changing.

ng-keypress: lagging behind 1 value. So the first value is undefined (this is a problem for my question). I am able to to do event.preventDefault();

Shold be: ng-keyup with event.preventDefault(); or ng-keypress with correct order

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
    $scope.myScore;
    $scope.limit = function(event, myScore){
       console.log(event, $scope.myScore, myScore);
       // do your code here myScore should be between (min-max)
       event.preventDefault(); 

    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

<!-- <input type="number" ng-model="myScore" min="0" max="200" ng-keypress="limit($event, myScore)"> -->

<input type="number" ng-model="myScore" min="0" max="200" ng-keyup="limit($event, myScore)">
{{myScore}}


</div>

Try using a previous value to fall back to. Then, since $scope.myScore will be undefined whenever it is given a value that falls outside of what's permitted by your input , check for that in your IF.

HIH

 var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.limit = function(e) { console.log( $scope.prevScore,$scope.myScore) if ($scope.myScore === undefined){ $scope.myScore = $scope.prevScore } $scope.prevScore = $scope.myScore; } $scope.forInitialValue = function(e) { if ($scope.myScore === undefined){ $scope.myScore = "" } $scope.prevScore = $scope.myScore; } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> <input type="number" ng-model="myScore" min="0" max="200" ng-change="limit($event)" ng-keydown="forInitialValue($event)"> {{myScore}} </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM