0

I have a tiny directive which simulates 'keydown' event on element click. It works completely fine but I would like like to create a more generic one by having the possibility to pass the 'keydown' value directly from the view.

Could you please help me to understand how the feature works in angular as some of them still bit confusing :) Thanks in advance.

My directive:

app.directive('simulateKeydown', [function(){
    return function(scope, element, attr){
        var e = jQuery.Event("keydown");
        e.which = 36;
        element.bind('click', function(){
            $(element).trigger(e);
        })

    }
}])

Current view:

<div simulate-keydown></div>

Desired view:

<div simulate-keydown="36"></div>

2 Answers 2

1

The attr argument (here return function(scope, element, attr)) holds all your attributes. So simply use it.

app.directive('simulateKeydown', [function(){
    return function(scope, element, attr){
        var e = jQuery.Event("keydown");
        e.which = parseInt(attr.simulateKeydown); // the value you gave it
        element.bind('click', function(){
            $(element).trigger(e);
        })
    }
}])

You can then use the directive as desired

<div simulate-keydown="36"></div>   
Sign up to request clarification or add additional context in comments.

2 Comments

In this case, it stops working. Although, when console.log(attr.simulateKeydown) it returns the value I passed to the directive in the view, but the event is not triggering
Yes, now works :) Thanks for you help, it's all clear!
1
<script>

var app = angular.module("myApp", []);
app.directive('simulateKeydown', [function(){
    return function(scope, element, attr){
        var e = jQuery.Event("keydown");
        e.which = attr.key;
        element.bind('click', function(){
            $(element).trigger(e);
        })

    }
}])

</script>
<div ng-app="myApp">
    <div simulate-keydown data-key="36"></div>
</div>

1 Comment

Thanks for the response, also very useful!

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.