Pares
Pares

Reputation: 57

How to fire a function with Search button as well as the Enter button on keyboard in Angular JS?

I have a Search field which currently fires when the Search button is clicked after a text input is given in the field. The code is as following:

<div class="form-group">
  <input type="text" class="form-control" id="Search" ng-model="searchkey">
</div>
<button type="submit" ng-click="searchfunc(searchkey)">
  Search
</button>

How do I fire this Search through the Enter key on the keyboard as well when an input is entered on the Search field?

Upvotes: 1

Views: 322

Answers (1)

P.S.
P.S.

Reputation: 16384

HTML:

<input type="text" class="form-control" id="Search" ng-model="searchkey" ng-keydown="myFunc($event)">

Controller:

$scope.myFunc = function(keyEvent) {
  if (keyEvent.which === 13) {
    // do stuff
    // here you can call the function and pass a parameter: "searchfunc($scope.searchkey);"
  }
}

Here is the working example: http://jsfiddle.net/Sj4ZU/62/

Upvotes: 2

Related Questions