Emil Gurbanov Emil Gurbanov - 14 days ago 7
AngularJS Question

How to create a directive with dynamic value in AngularJS

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>

Answer

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>   
Comments