我有一个输入:文本字段,其中应用了一些验证规则,即required,ng-maxlength。我已经创建了一个指令来捕获该输入字段上的TAB键。问题是单击TAB和Backspace,错误消息未隐藏和显示。这是jsfiddle:http://jsfiddle.net/36qp9ekL/199/
.directive('allowTab', function () {
return {
require: 'ngModel',
link: function (scope, ele, attrs, c) {
ele.bind('keydown keyup', function (e) {
if(e.keyCode === 9 && e.type == 'keydown'){
// get caret position/selection
var val = this.value,
start = this.selectionStart,
end = this.selectionEnd;
// set textarea value to: text before caret + tab + text after caret
this.value = val.substring(0, start) + '[TAB]' + val.substring(end);
// put caret at right position again
this.selectionStart = this.selectionEnd = start + 5;
scope.$digest();
e.preventDefault();
return false;
}
if(e.keyCode === 8 && e.type == 'keydown'){ //on backspace remove the [Tab]
var val = this.value;
var i = this.selectionEnd;
if(i > 4) {
var prev = val.substring(i-5,i);
if(prev == '[TAB]') {
this.value = val.substring(0, i-5)+ val.substring(i);
scope.$digest();
e.preventDefault();
}
}
}
});
}
}
步骤:
1) Enter 'a'
2) Remove 'a' by pressing backspace
error will appear
3) Now click TAB
issue: error is not removed