我想捕捉下面文本框上的回车键事件。为了更清楚地说明这一点,我使用ng-repeat填充tbody。下面是HTML:

<td><input type="number" id="closeqty{{$index}}" class="pagination-right closefield" 
    data-ng-model="closeqtymodel" data-ng-change="change($index)" required placeholder="{{item.closeMeasure}}" /></td>

这是我的模块:

angular.module('components', ['ngResource']);

我使用一个资源来填充表,我的控制器代码是:

function Ajaxy($scope, $resource) {
//controller which has resource to populate the table 
}

当前回答

我最简单的方法是使用angular内置指令:

ngk, ngk或ngke是的。

通常,我们希望为已经由ng-click处理的内容添加键盘支持。

例如:

<a ng-click="action()">action</a>

现在,让我们添加键盘支持。

由回车键触发:

<a ng-click="action()" 
   ng-keydown="$event.keyCode === 13 && action()">action</a>

空格键:

<a ng-click="action()" 
   ng-keydown="$event.keyCode === 32 && action()">action</a>

空格或输入键:

<a ng-click="action()" 
   ng-keydown="($event.keyCode === 13 || $event.keyCode === 32) && action()">action</a>

如果你使用的是现代浏览器

<a ng-click="action()" 
   ng-keydown="[13, 32].includes($event.keyCode) && action()">action</a>

关于keyCode的更多信息: keyCode已弃用,但支持良好的API,你可以使用$ eventt。请输入受支持的浏览器。 详见https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

其他回答

html

<textarea id="messageTxt" 
    rows="5" 
    placeholder="Escriba su mensaje" 
    ng-keypress="keyPressed($event)" 
    ng-model="smsData.mensaje">
</textarea>

controller.js

$scope.keyPressed = function (keyEvent) {
    if (keyEvent.keyCode == 13) {
        alert('presiono enter');
        console.log('presiono enter');
    }
};

另一种方法是使用标准指令ng-keypress="myFunct($event)"

然后在你的控制器中你可以有:

...

$scope.myFunct = function(keyEvent) {
  if (keyEvent.which === 13)
    alert('I am an alert');
}

...

这个呢?:

<form ng-submit="chat.sendMessage()">
    <input type="text" />
    <button type="submit">
</form>

现在,当你在输入后按回车键时,表单知道如何处理它。

你需要添加一个指令,像这样:

Javascript:

app.directive('myEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.myEnter);
                });

                event.preventDefault();
            }
        });
    };
});

HTML:

<div ng-app="" ng-controller="MainCtrl">
    <input type="text" my-enter="doSomething()">    
</div>

我有点晚了。但我发现了一个更简单的解决方案,使用自动对焦。这可能是有用的按钮或其他弹出对话框:

<button auto-focus ng-click="func()按钮“> < / >

这应该是好的,如果你想按下按钮onSpace或Enter单击。