我想捕捉下面文本框上的回车键事件。为了更清楚地说明这一点,我使用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 
}

当前回答

所有你需要做的事情是获得事件如下:

console.log(angular.element(event.which));

指令可以做到这一点,但你不能这样做。

其他回答

这是我在开发一个有类似需求的应用程序时得出的结论, 它不需要写一个指令,它是相对简单的告诉它做什么:

<input type="text" ng-keypress="($event.charCode==13)?myFunction():return" placeholder="Will Submit on Enter">
(function(angular) {
  'use strict';
angular.module('dragModule', [])
  .directive('myDraggable', ['$document', function($document) {
    return {
      link: function(scope, element, attr) {
         element.bind("keydown keypress", function (event) {
           console.log('keydown keypress', event.which);
            if(event.which === 13) {
                event.preventDefault();
            }
        });
      }
    };
  }]);
})(window.angular);

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');
    }
};

我认为使用文档。Bind更优雅一些

constructor($scope, $document) {
  var that = this;
  $document.bind("keydown", function(event) {
    $scope.$apply(function(){
      that.handleKeyDown(event);
    });
  });
}

获取文档到控制器构造函数:

controller: ['$scope', '$document', MyCtrl]

我最简单的方法是使用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