<input id="myid" type="number" ng-model="maxVal" ng-change="maxValCheck()"
max="5" min="1" value="1"/>
在 Controller 中
$scope.maxVal;
$scope.maxValCheck = function() {
if($scope.maxVal> 5) {
$scope.maxVal= 5;
}
}
我想当输入字段的值超过5时将其更改为5。但它不起作用。我究竟做错了什么?您建议有更好的方法吗?
最佳答案
最好使用指令。
示例:
<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(); }); } } }]);
关于javascript - 如何使用 angularjs 编辑输入值超出限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56760922/