我有一个自定义指令,该指令是在input上的ng-model过滤器之后做出的,该指令将输入仅限制为数字:
.directive('onlydigitinput', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
var transformedInput = inputValue.toLowerCase().replace(/ /g, '')
.replace(/[^0-9]+/g, '');
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
})
单独使用时效果很好,但显然与所需的标准指令一起使用时,它开始失败。
我使用以下HTML(玉器语法):
input(type='text' , required, onlydigitinput, min='1', max='99', maxlength='2')
(我不使用type ='number',因为它与maxlength混淆:在Chrome中,对于输入type =“ number”,maxlength被忽略,并且也忽略了我的指令)
当我输入数字时,它可以正常工作。栏位有效。当我尝试输入数字然后再输入字母时,它可以正常工作:该字段有效,并且我无法输入非数字。但是,当我从非数字开头时,该字段无效,但是我仍然可以输入字母,并伴有以下错误:
TypeError: Cannot read property 'toLowerCase' of undefined
at http://localhost:3000/scripts/core/directives/systemDirectives.js:63:54
指的是上面指令中toLowerCase的使用。请建议我如何清除此错误,并使我的指令在后一种情况下也能正常运行,并避免该错误。
您在输入字段上有一个必填字段验证器。因此,当您将字段设置为blank(“”)时-键入非数字时会发生。该值变为undefined。
var transformedInput = inputValue.toLowerCase().replace(/ /g, '')
.replace(/[^0-9]+/g, '');
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
在上面的代码之上添加以下内容:
if(!inputValue) return ;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句