angular.js keypress指令事件神秘地没有触发

时间:2015-08-15 19:47:28

标签: javascript angularjs events angularjs-directive angular-digest

我按照这个例子Submit form on pressing Enter with AngularJS

但我无法让它发挥作用。这完全令人费解。为什么按键事件不会被我的指令困住?

http://plnkr.co/edit/A9oio2F61yHssE49aiCb?p=preview

app.directive('enterKey', function($log) {
    return function(scope, element, attrs) {
        element.bind("keydown keypress", function(event) {
            if(event.which === 13) {

                scope.$apply(function(){
                    scope.$eval(attrs.ngEnter, {'event': event});
                });
                event.preventDefault();
            }
        });
    };
});

1 个答案:

答案 0 :(得分:1)

当您更改指令名称时,指令attrs.ngEnter中的复制粘贴错误应为attrs.enterKey

scope.$apply(function(){
    scope.$eval(attrs.enterKey, {'event': event});
});

此外,您需要在event方法中添加alertMe参数才能接受事件

$scope.alertMe = function(event) {
    alert('I am alerted!');
}
相关问题