Skip to content

Instantly share code, notes, and snippets.

@1player
Last active March 20, 2016 11:24
Show Gist options
  • Save 1player/9595534 to your computer and use it in GitHub Desktop.
Save 1player/9595534 to your computer and use it in GitHub Desktop.
Angular directive to clear a form input with the ESC key
<input type="text" ng-model="searchQuery" clear-with-esc>
// Clear a form input with the ESC key
app.directive('clearWithEsc', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, element, attrs, controller) {
element.on('keydown', function(ev) {
if (ev.keyCode != 27) return;
scope.$apply(function() {
controller.$setViewValue("");
controller.$render();
});
});
},
};
});
@teyc
Copy link

teyc commented Feb 27, 2016

$rollbackViewValue() should work better than $setViewValue as it reverts to the original value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment