How to use a keypress event in AngularJS?

2018-12-31 23:34发布

I want to catch the enter key press event on the textbox below. To make it more clear I am using a ng-repeat to populate the tbody. Here is the 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>

This is my module:

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

I am using a resource to populate the table and my controller code is:

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

19条回答
君临天下
2楼-- · 2018-12-31 23:43
(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);
查看更多
旧时光的记忆
3楼-- · 2018-12-31 23:44

You need to add a directive, like this:

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>
查看更多
明月照影归
4楼-- · 2018-12-31 23:44

Another simple alternative:

<input ng-model="edItem" type="text" 
    ng-keypress="($event.which === 13)?foo(edItem):0"/>

And the ng-ui alternative:

<input ng-model="edItem" type="text" ui-keypress="{'enter':'foo(edItem)'}"/>
查看更多
美炸的是我
5楼-- · 2018-12-31 23:44

You can use ng-keydown ="myFunction($event)" as attribute.

<input ng-keydown="myFunction($event)" type="number">

myFunction(event) {
    if(event.keyCode == 13) {   // '13' is the key code for enter
        // do what you want to do when 'enter' is pressed :)
    }
}
查看更多
姐姐魅力值爆表
6楼-- · 2018-12-31 23:44

I think using document.bind is a bit more elegant

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

To get document to the controller constructor:

controller: ['$scope', '$document', MyCtrl]
查看更多
裙下三千臣
7楼-- · 2018-12-31 23:44

How about just

<input (keyup.enter)="doWhatYouWant()">
查看更多
登录 后发表回答