How do I insert a tab character (indent) inside a textarea using AngularJS?
I tried this:
<textarea class="form-control" rows="10" ng-model="vm.text" ng-keydown="vm.handleTabKey($event)"></textarea>
With function handleTabKey being:
function handleTabKey(e) {
if (e.which === 9) {
e.preventDefault();
var start = e.target.selectionStart;
var end = e.target.selectionEnd;
vm.text = vm.text.substring(0, start) + '\t' + vm.text.substring(end);
e.target.selectionStart = e.target.selectionEnd = start + 1;
}
};
Although the tab character is inserted, the caret position is always at the end, despite the last line.
Another problem is that if I insert one or more new lines at the end, pressing tab will insert a tab at the end of the line before the new lines, as if ignoring them. In other words, vm.text doesn't contain those new lines until non-whitespace characters are entered.