【问题标题】:directive doesn't function properly指令无法正常运行
【发布时间】:2016-05-18 05:09:15
【问题描述】:

我正在尝试编写一个限制用户输入的指令。在示例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;
        }
    }

【问题讨论】:

  • 你能提供一个小提琴吗?我的猜测是你必须使用keydown 事件而不是keypress。此外,您可能希望明确指定 parseInt 的基数,例如 parseInt(number, 10),因为旧版本的 EcmaScript 使用八进制作为默认基数。

标签: angularjs typescript angular-directive


【解决方案1】:

我认为您想使用 if is 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();
                }

            }
        });

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    • 2015-12-08
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多