指令不能正常运行

时间:2016-02-08 13:52:49

标签: angularjs typescript angular-directive

我试图写一个限制用户输入的指令。在示例limit-directive="2"上,用户只能在输入字段中键入两个字符。

我的问题是我的指令不起作用。它被调用但没有停止按键返回false或event.preventDefault();。 关于我缺少什么的任何想法?

export class limitDirective implements angular.IDirective {
        restrict = 'A';

        constructor() {
            if(console) console.log('limit directive invoked')
        }

        link = (scope: angular.IScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes) => {
            var limit = parseInt(attrs.limitDirective);

            angular.element(element).on("keypress", function(event) {
                if (this.value.length >= limit){
                    var allowedKeys = [8, 9, 13, 35, 36, 37, 38, 39, 40, 46];
                    var key = event.which || event.keyCode;

                    if (allowedKeys.indexOf(key) < 0 ){
                        event.preventDefault();
                    }

                }
            });
        }

        static factory(): angular.IDirectiveFactory {
            const directive = () => new limitDirective();
            return directive;
        }
    }

1 个答案:

答案 0 :(得分:0)

我认为你想使用if less than or equals来代替greater that or equals运算符。我怀疑this对应于事件回调中的元素。我建议你这样做:

 element.bind("keypress", function(event) {
                if (element[0].value.length <= limit){
                    var allowedKeys = [8, 9, 13, 35, 36, 37, 38, 39, 40, 46];
                    var key = event.which || event.keyCode;
                if (allowedKeys.indexOf(key) < 0 ){
                    event.preventDefault();
                }

            }
        });