如何在angular.js中以编程方式触发<input type =“text”/>的enter keypress事件?

时间:2016-02-11 14:35:34

标签: angularjs javascript-events

我有这个元素,其“enter”按键事件我想通过另一个按钮的ng点击来触发。

即,

让我们说:

<button ng-click="clickEvent()"></button>
<input type="text" id="textbox"></input>

Plnkr在这里:http://plnkr.co/edit/tEVoHAAcyqQzWpc9iYpo?p=preview

请帮忙!

1 个答案:

答案 0 :(得分:0)

您可以通过创建角度指令来实现此目的。 JSFiddle供参考 - Demo 单击Click Me !按钮后查看控制台。希望这会有所帮助!

<body ng-app="myApp" ng-controller="myController">
  <h1>Hello JSFiddle!</h1>
  <button id="btnClick" ng-click="clicked()" capture-keypress>Click Me !</button>
  <input ng-keydown="keypress($event)" id="txtInput">
</body>


app.controller('myController', function($scope) {
  $scope.keypress = function($event) {
    console.log('Key Event Fired');
  };
});

app.directive('captureKeypress', function($timeout) {
  return {
    scope: true,
    link: function(scope, element, attrs) {
      scope.clicked = function() {
        $timeout(function() {
          element.siblings('#txtInput').trigger('keydown');
        })
      }
    }
  }
});