Skip to content

Instantly share code, notes, and snippets.

@EpokK
Last active September 26, 2025 13:35
Show Gist options
  • Select an option

  • Save EpokK/5884263 to your computer and use it in GitHub Desktop.

Select an option

Save EpokK/5884263 to your computer and use it in GitHub Desktop.
ngEnter directive if you can use submit form(https://twitter.com/ririlepanda)
app.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if(event.which === 13) {
scope.$apply(function(){
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
@jose-marin

jose-marin commented Aug 11, 2016

Copy link
Copy Markdown

You don't need to use eval if you bind the function passed. It also makes the scope isolate, so the directive doesn't depend on a parent controller.

app.directive('onEnter', function() {
    return {
        restrict: "A",
        scope: {
            action: "&onEnter"
        },
        link: function(scope, element, attrs) {
            element.on("keydown keypress", function(event) {
                if(event.which === 13) {
                    scope.$apply(scope.action);
                    event.preventDefault();
                }
            });
        }
    };
});

@adilbenmoussa

Copy link
Copy Markdown

No was is asking the question if element.on("keydown keypress", fun) should be unbind? when destroying the element?

@georgeportillo

georgeportillo commented Sep 21, 2016

Copy link
Copy Markdown

@jose-marin thanks for the snippet!

@michalpanek

Copy link
Copy Markdown

attrs is no needed.

  link: function(scope, element, attrs) {

@w0nderw0man

Copy link
Copy Markdown

@jbaroudi thanks for typescript users

@developerant

Copy link
Copy Markdown

@jose-marin - nicely done. Thanks

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