Featured image for zzEnter

zzEnter

le par Benjamin


Hi,

Today, I’ll share my first tip for AngularJs. This is something very simple but this can be usefull.

zzEnter

zzEnter is a directive that allows you to call a function when using “Enter” key on your keyboard when typing an input.

Code

angular.module('zzEnter', [])
.directive('zzEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.zzEnter);
                });
                event.preventDefault();
            }
        });
    };
})

How to

<script src="js/zzEnter.js"></script>
angular.module('myApp', ['zzEnter'])
// ...

So, now when you use “Enter” key on this input, you should be alerted with “Hello, [what you entered in the input]!” .


Did you like it ? Did you find it usefull? let me know in the comments …