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

当前回答

你可以使用ng-keydown, ng-keyup, ng-press,像这样。

触发一个函数:

   <input type="text" ng-keypress="function()"/>

或者如果你有一个条件,比如当他按下escape(27是键) 转义代码)

 <form ng-keydown=" event.which=== 27?cancelSplit():0">
....
</form>

其他回答

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

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

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

你可以使用ng-keydown, ng-keyup, ng-press,像这样。

触发一个函数:

   <input type="text" ng-keypress="function()"/>

或者如果你有一个条件,比如当他按下escape(27是键) 转义代码)

 <form ng-keydown=" event.which=== 27?cancelSplit():0">
....
</form>

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

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

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

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

这是我的指示:

mainApp.directive('number', function () {
    return {
        link: function (scope, el, attr) {
            el.bind("keydown keypress", function (event) {
                //ignore all characters that are not numbers, except backspace, delete, left arrow and right arrow
                if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 8 && event.keyCode != 46 && event.keyCode != 37 && event.keyCode != 39) {
                    event.preventDefault();
                }
            });
        }
    };
});

用法:

<input number />

这是对EpokK答案的扩展。

我有同样的问题,必须调用一个作用域函数时,enter被推到一个输入字段。但是,我还想将输入字段的值传递给指定的函数。这是我的解决方案:

app.directive('ltaEnter', function () {
return function (scope, element, attrs) {
    element.bind("keydown keypress", function (event) {
        if(event.which === 13) {
          // Create closure with proper command
          var fn = function(command) {
            var cmd = command;
            return function() {
              scope.$eval(cmd);
            };
          }(attrs.ltaEnter.replace('()', '("'+ event.target.value +'")' ));

          // Apply function
          scope.$apply(fn);

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

});

在HTML中的用法如下:

<input type="text" name="itemname" lta-enter="add()" placeholder="Add item"/>

向EpokK的回答致敬。