这段jquery代码在angular指令中不起作用

piece of jquery code is not working in angular directive

本文关键字:指令 不起作用 angular jquery 代码 这段      更新时间:2023-09-26

我有一个指令,里面有几个输入,当按下回车键时,我需要一个特定的输入来执行函数。

这是我执行函数所需要的输入。

<input type="text" class="form-control" ng-model="cep" id="inputcep">

我有一个jquery函数,它使用了一个掩码插件和一个keypress监听器,该监听器阻止enter键的默认操作并执行该函数。我的问题是没有调用按键,但正在应用掩码:/

$(document).ready(function () {
         $('#inputcep')
              .keypress(function(ev){
                  console.log(ev);
                  if(ev.keyCode == 13){
                       ev.preventDefault();
                       scope.searchCep(scope.cep);
                   }
            })
            .mask('00000-000');
});

使用angular而不是jQuery:

https://docs.angularjs.org/api/ng/directive/ngKeypress

按如下方式创建自定义指令。

指令

app.directive('customDir', function() {
    return function(scope, element, attrs) {
        element.bind("keydown keypress", function(event) {
            element.keypress(function(ev) {
                console.log(ev);
                if (ev.keyCode == 13) {
                    ev.preventDefault();
                    scope.searchCep(scope.cep);
                }
            }).mask('00000-000');
        });
    };
});