编程语言
首页 > 编程语言> > javascript-ng-keydown事件使用自定义指令两次触发

javascript-ng-keydown事件使用自定义指令两次触发

作者:互联网

我使用了下面链接中的代码,因为我希望仅在用户使用桌面时才将指令添加到特定的文本区域.这个相同的textarea还具有ng-keydown指令,奇怪的是,在添加此代码时,每次按下的每个新键都会被双击.

知道为什么会发生或如何解决吗?

angularjs-conditional-directive-only-on-desktop

更新:

另外一个奇怪的行为是,当您删除单词的最后一个字符时,它会自动删除前一个空格(如果有的话).

要对其进行测试,请打开控制台并检查是否按任意键,都会两次出现“ teste1”消息

jsFiddle

此代码的相关部分:

myApp.directive('notOnMobile', function($compile) {
    // Perform detection.
    // This code will only run once for the entire application (if directive is present at least once).
    // Can be moved into the compile function if detection result needs to be passed as attribute.
    var onMobile = false;

    return {
        compile: function compile(tElement, tAttrs) {
            if (!onMobile) tElement.attr(tAttrs.notOnMobile, '');
            tElement.removeAttr('not-on-mobile');

            return function postLink(scope, element) {
                $compile(element)(scope);
            };
        }
    };
});

<textarea ng-model="main.queryString"
          rows="1"
          ng-keydown="main.textareaAction($event)"
          not-on-mobile="auto-focus"></textarea>

解决方法:

您将需要为指令添加终端和优先级.因此它不会两次编译元素:

myApp.directive('notOnMobile', function($compile) {
// Perform detection.
// This code will only run once for the entire application (if directive is present at least once).
// Can be moved into the compile function if detection result needs to be passed as attribute.
var onMobile = false;

return {
    terminal:true,
    priority:1001,
    compile: function compile(tElement, tAttrs) {
        if (!onMobile) tElement.attr(tAttrs.notOnMobile, '');
        tElement.removeAttr('not-on-mobile');

        return function postLink(scope, element) {
            $compile(element)(scope);
        };
    }
};
});

在这里找到工作代码示例https://jsfiddle.net/h1gr0dwp/

编辑:

您可以在这里找到关于端子和优先级的说明Add directives from directive in AngularJS

标签:angularjs,angularjs-directive,javascript
来源: https://codeday.me/bug/20191119/2036980.html