-
-
Save jaumebonet/55a9ac0e24b57558b8b1 to your computer and use it in GitHub Desktop.
React to Press Enter, the AngularJS way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div> | |
<input | |
type = "text" | |
placeholder = "Something to say" | |
ng-model = "target_variable" | |
ng-pattern = 'pattern_variable' | |
jb-on-enter = "executeCommand()" | |
> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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