0

I have this directive which sets focus on an input field when it appears and hides it when it loses focus or the esc/enter/tab key is pressed. It works just fine, but I wanted to know if there was a way I could pass in an array or object of keys (and event types) instead of hard coding the keys and events into the directive itself? Here is the code:

.directive('bindKeys', function ($timeout) {

    return {
        restrict: 'A',
        scope: {
            trigger: '='
        },

        link: function(scope, elem){

            elem.bind('keydown keypress blur', function (event) {
                    if(event.which === 13 || event.which === 9 || event.which === 27 || event.type === 'blur') {
                        event.preventDefault();
                        $timeout(function(){
                            scope.trigger.property = false;
                        });
                    }
                });
            scope.$watch('trigger.property', function(value) {

                if(value === true) {
                    $timeout(function() {
                        elem[0].focus();
                    });
                }
            });
        }
    };
});

The element looks like this:

<input bindKeys trigger='trigger'></input>

Thanks

1
  • you could pass your config array as an attribute Commented Mar 6, 2015 at 21:51

1 Answer 1

1

You sure can. Have some module provide your array

.value('events', ['blur', 'keypress'])

And then have them inject into you directive (events var name must match key above).

.directive('bindKeys', function ($timeout, events) {
    // ...
    element.bind(events.join(' '), function() {})
}

The alternative syntax to inject your array is by explicitly defining names to vars

.directive('bindKeys', ['$timeout', 'events', function ($timeout, events) {})

See more on dependency injection here: https://docs.angularjs.org/guide/di

and on modules here: https://docs.angularjs.org/guide/module

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry it took so long to reply, but this was just what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.