angularjs指令允许制表符

时间:2015-04-29 12:18:29

标签: javascript angularjs

我正在尝试创建一个angularjs指令,该指令允许在文本字段上输入制表符。它的工作部分但错误没有正确显示。我也想要这个领域。这是我的代码

.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);
                        }
                    }
                });
             }
        }
    });

这里是jsfiddle:http://jsfiddle.net/36qp9ekL/184/

3 个答案:

答案 0 :(得分:4)

您是否尝试在制表符后将焦点保留在文本框中?

您必须使用preventDefault()方法:

// ...
                // 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;

// ...

http://jsfiddle.net/36qp9ekL/186/

答案 1 :(得分:1)

更新文本框值并在jQuery中设置验证 - 而不是在角度生命周期中。要及时更新前端,需要调用范围。$ digest()将角度模型与dom同步。

                // put caret at right position again
                this.selectionStart = this.selectionEnd = start + 1;

                c.$setValidity('allowTab', true);
                scope.$digest();

http://jsfiddle.net/36qp9ekL/187/

答案 2 :(得分:0)

我扩展了迈克尔版本并使其正常工作,这里是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();
}