Angularjs directive to specify tab character
I am trying to create an angularjs directive that will allow a tab character to be injected into a textbox. Its work is partial, but the error is not displayed correctly. I want this field to be required as well. Here is my code
.directive('allowTab', function () {
return {
require: 'ngModel',
link: function(scope, ele, attrs, c) {
ele.bind('keydown keyup', function(e) {
var val = this.value;
if (e.keyCode === 9 && e.type === 'keydown') { // tab was pressed
// get caret position/selection
var start = this.selectionStart,
end = this.selectionEnd;
// set textarea value to: text before caret + tab + text after caret
this.value = val.substring(0, start) + '\t' + val.substring(end);
// put caret at right position again
this.selectionStart = this.selectionEnd = start + 1;
c.$setValidity('allowTab', true);
// prevent the focus lose
return false;
}
else if(e.keyCode !== 9 && e.type === 'keyup') {
if(val === '') {
c.$setValidity('allowTab', false);
}
else {
c.$setValidity('allowTab', true);
}
}
});
}
}
});
here is a jsfiddle: http://jsfiddle.net/36qp9ekL/184/
+3
source to share
3 answers
Are you trying to keep the focus in the textbox after the tab character?
You have to use preventDefault () method:
// ...
// set textarea value to: text before caret + tab + text after caret
this.value = val.substring(0, start) + '\t' + val.substring(end);
// put caret at right position again
this.selectionStart = this.selectionEnd = start + 1;
c.$setValidity('allowTab', true);
e.preventDefault();
// prevent the focus lose
return false;
// ...
+4
source to share
You are updating the textbox value and setting the validation in jQuery, not in the angular lifecycle. To update the interface in time, you need to call the scope. $ Digest () to sync angular model with dom.
// put caret at right position again
this.selectionStart = this.selectionEnd = start + 1;
c.$setValidity('allowTab', true);
scope.$digest();
+1
source to share
I extended Michael's version and got it working exactly what I was looking for, here is the jsfiddle: http://jsfiddle.net/36qp9ekL/190/
else if (e.keyCode !== 9 && e.type === 'keyup') {
var hasTab = val.indexOf('\t') > -1;
if(hasTab){
c.$setValidity('allowTab', true);
}
else if(val == '') {
c.$setValidity('allowTab', false);
}
else {
c.$setValidity('allowTab', true);
}
scope.$digest();
}
0
source to share