如何使用AngularJS在超过限制时重置输入值
我们的任务是在用户输入的数字超过某个限制时,使用angularJS来处理一个输入域。我们定义一个limitTo指令,并在一个HTML输入元素上使用它。这个指令用于处理所有溢出的限制。该指令在按键事件上调用一个函数,在这里我们可以检查极限。
示例1:本例将用户输入的值设置为0,如果其限制超过100。
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js">
</script>
</head>
<body ng-controller="MyController"
style="text-align:center;">
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>
Edit an input value when
it exceeds the limit
</h3><br>
<!-- Custom directive limit-to -->
<input limit-to="100"
type="number"
ng-model="val"> {{val}}
<script type="text/javascript">
angular.module('myApp', []).controller('MyController',
['scope', function(scope) {
// Value to ng model the input
scope.val;
}]).directive("limitTo",
['timeout', function(timeout) {
// Declaration of custom directive
return {
restrict: "A",
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.limitTo);
elem.on("keypress", function(e) {
timeout(function() {
if(parseInt(e.target.value) > limit) {
// Handle change here
scope.val = 0;
scope.$apply();
e.preventDefault();
}
});
});
}
}
}]);
</script>
</body>
</html>
输出:只要用户超过100,该值就会被设回0。
例子2:在这个例子中,我们根据输入限制来改变文本。如果输入的值小于0,那么它就变成0;如果它的值大于100,那么它就变成100,否则就保持原样。
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js">
</script>
</head>
<body ng-controller="MyController"
style="text-align: center">
<h1 style="color: green">GeeksforGeeks</h1>
<h3>
Edit an input value when
it exceeds the limit
</h3>
<!-- Custom directive limit-to -->
<input limit-to="100"
type="number"
ng-model="val" /><br />
{{text}}
<script type="text/javascript">
angular.module('myApp', []).controller('MyController',
['scope',function(scope) {
// Value to ng model the input
scope.val;
scope.text = 'Inside Limit';
},
]).directive('limitTo',
['timeout',function(timeout) {
// Declaration of custom directive
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.limitTo);
elem.on('keypress', function(e) {
timeout(function() {
if(parseInt(e.target.value)>limit) {
// Handle change here if greater
scope.text = 'Outside limit (greater)';
scope.val = 100;
scope.apply();
e.preventDefault();
} else if(parseInt(e.target.value) < 0) {
scope.text = 'Outside limit (smaller)';
scope.val = 0;
scope.apply();
e.preventDefault();
} else {
scope.text = 'Inside Limit';
scope.apply();
e.preventDefault();
}
});
});
},
};
},
]);
</script>
</body>
</html>
输出: