I found a solution that does not require a directive. I already used ng-change to capture every keystroke and perform a search, but pressing Enter would put my SharePoint page in edit mode. SharePoint does not allow you to access the form tag, so most of these solutions did not help me.
This solution was much simpler and kept my code in one place: I have an ng-change and ng-keypress event pointing to the same event handler, vm.txtSearchChange ():
HTML
<input id="txtSearch" type="text" style="width: 400px;" ng-change="vm.txtSearchChange()" ng-keypress="$event.keyCode == 13 ? vm.txtSearchChange($event) : null" ng-model="vm.Search" ng-model-options="{debounce: 200}"/>
Note that the ng-change event does not pass the $ event attribute and handles valid keystrokes, while the ng-keypress event is only for the enter key.
SCRIPT
vm.txtSearchChange = function ($event) { if ($event) { $event.preventDefault(); return; } console.log("Search: " + vm.Search); vm.showResults(); }
When the value of $ event is not NULL, this is the enter key, we call protectDefault () and do not process further. When $ event is null, this is a valid key, and we pass it to vm.showResults () for processing.
Cigardoug
source share