Angularjs 防止输入类型编号上的maxLength
我花了一些时间才弄明白这一点,但是有人能发布一个更干净的方法来限制输入type='number'中的位数吗。其中一个问题是,如果$scope.variable=null…表示输入字段中没有任何内容,则会引发错误Angularjs 防止输入类型编号上的maxLength,angularjs,input,maxlength,Angularjs,Input,Maxlength,我花了一些时间才弄明白这一点,但是有人能发布一个更干净的方法来限制输入type='number'中的位数吗。其中一个问题是,如果$scope.variable=null…表示输入字段中没有任何内容,则会引发错误 <input type="number" model='modalName' ng-change="monitorLength('modalName',16)"> 然后,我需要在此基础上进行扩展,以仅说明数字,防止任何非数字字符包括“.”和“,”符号: var reg
<input type="number" model='modalName' ng-change="monitorLength('modalName',16)">
然后,我需要在此基础上进行扩展,以仅说明数字,防止任何非数字字符包括“.”和“,”符号:
var reg = new RegExp(/^\d+$/) ;
$scope.monitorLength = function (modal,maxLength) {
if ($scope[modal] != null) {
var len = $scope[modal].toString() ;
if (len.length > maxLength) {
$scope[modal] = parseInt(len.substring(0, maxLength));
} else if (!reg.test(len)) {
$scope[modal] = parseInt(len.substring(0, len.length-2));
}
}
}
是否有方法提取负责调用ng更改的ng模式?因此,调用只能是:ng change=monitorLength10。然后在函数中以某种方式动态检索调用的ng模式?这是一种更干净的限制数量的方法,使用ngMaxlength:
<input type="number" model='modalName' ng-maxlength="16">
您可以找到更多属性和信息
是否有方法提取负责调用ng更改的ng模式
对。您可以定义一个指令并要求使用ngModelController
正如@rolinger在另一个答案中所述,使用内置指令不会阻止用户输入无效字符,它们只是将模型标记为无效。您不能在输入元素上仅使用最小值和最大值吗?很少有浏览器不支持angular,因为它包装元素并将它们绑定到$scope特定的HTML输入参数不起作用,或者它们被忽略。这不是你链接到的页面所建议的ng maxlength吗?对不起,从图表复制粘贴,你是对的,它的ng maxlength否,ng maxlength实际上并不阻止用户键入超过16个字符。$scope.variable中只存储了16个字符…但用户在视觉上仍会看到超过16个字符。以上是一种防止实际输入字段中字符溢出的方法。从角度文档中可以看出:注意:在使用普通maxlength属性时也添加了此指令,但有两个区别:ngMaxlength未设置maxlength属性,因此HTML5约束验证不可用。
<input type="number" model='modalName' ng-maxlength="16">
.directive('maxNum', function(){
return {
require: '^ngModel',
link: function($scope, elem, attrs){
// here you can add formatters/parsers to the ngModel
// to affect the change on the ngModel.$viewValue.
}
}
})