Sean Bugeja Sean Bugeja - 15 days ago 6
AngularJS Question

AngularJS directive to make input respond on enter

I apologize if the question is vague, I'm not quite sure how else to explain what I need. There are some dirty options which come to mind, but I'm a novice AngularJS coder and I feel there is a clean simple method to implement this with directives maybe?

What I need is an input box that waits for an ENTER keypress, and fires, and action when it gets it. The action is a simple get from an external JSON object based on the input entered before the enter was pressed.

The field should also reset to empty on each newline keypress.

:

Answer

Ng-submit to the rescue ! You can easily make it work by wrapping the input in a form (that has a name). One big plus : this will work on mobile, they'll have a shortcut to "submit" next to the keyboard.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>

  
<form 
  name="theFormNeedsANameForNgSubmitToFire" 
  ng-submit="myScopeInfos='Enter pressed and mytext was '+mytext;mytext='';">

  <input type="text" ng-model="mytext"/>

</form>

<div>{{myScopeInfos}}</div>
</div>

Comments