我有一个自定义指令,是在filters on ng-model in an input之后创建的,将输入限制为数字:
.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(jade 语法):
input(type='text' , required, onlydigitinput, min='1', max='99', maxlength='2')
(我不使用 type='number' 因为它与 maxlength: maxlength ignored for input type="number" in Chrome 混淆,并且也忽略了我的指令)
当我输入数字时,它工作正常。字段有效。 当我尝试输入数字然后输入一些字母时,它工作正常:字段有效,并且我无法输入非数字。 但是当我从非数字开始时,字段无效,但我仍然可以输入字母,并伴有以下错误:
TypeError: Cannot read property 'toLowerCase' of undefined
at http://localhost:3000/scripts/core/directives/systemDirectives.js:63:54
指的是上面指令中 toLowerCase 的使用。请告知我如何清除此错误并使我的指令在后一种情况下也能正常执行,并避免该错误。
最佳答案
您的输入字段上有一个必填字段验证器。因此,当您将该字段设置为空白(“”)时 - 当您键入非数字时会发生这种情况。该值变为未定义。
var transformedInput = inputValue.toLowerCase().replace(/ /g, '')
.replace(/[^0-9]+/g, '');
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
在上面的代码之上添加以下内容:
if(!inputValue) return ;
关于javascript - Angular 要求指令打破了我自己的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24010990/