Skip to content

Instantly share code, notes, and snippets.

@jaumebonet
Forked from EpokK/ngEnter.js
Last active August 29, 2015 14:10
Show Gist options
  • Save jaumebonet/55a9ac0e24b57558b8b1 to your computer and use it in GitHub Desktop.
Save jaumebonet/55a9ac0e24b57558b8b1 to your computer and use it in GitHub Desktop.
React to Press Enter, the AngularJS way
<div>
<input
type = "text"
placeholder = "Something to say"
ng-model = "target_variable"
ng-pattern = 'pattern_variable'
jb-on-enter = "executeCommand()"
>
</div>
/* Adapted from EpokK's to check if a value has been passed to the input field through a ngModel.
This can work alone or if the input[type="text"] has a ngPattern filter.
Also, taken out the ng prefix to avoid possible confussion with regular Angular directives now
or in the future.
*/
app.directive('jbOnEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
var key = typeof event.which === "undefined" ? event.keyCode : event.which;
if(key === 13) {
var content = scope.$eval(attrs.ngModel);
if (typeof content != 'undefined' && content) {
scope.$apply(function (){
scope.$eval(attrs.jbOnEnter);
});
event.preventDefault();
}
}
});
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment