1

is it possible to use one event handler within other in link function of angular directive, something like this:

  app.directive('testDirective',function(){
   return{
    restrict:'A',
    link:function(scope, element, attrs) {

        element.bind('mousedown', function () {
            element.bind('keydown', function(evt) {
               console.log('pressed',evt);
            });
        });
    }
}});

3 Answers 3

2

Yes , there are situations where you required to nest your event functions , for ex as below ,where nested events will get binded once the parent event is triggered . as example below mouseenter , mouseleave will be triggered after click of the element

app.directive('myDirective',function(){


      return {
        restrict:'A',
        link:function(scope,element,attrs){

          element.on('click',function(){
            console.log("clicked")
            element.on('mouseenter',function(){

              console.log("hello entered mouse");
            });

            element.on('mouseleave',function(){
              console.log("helllo leaving")
            })

          })
        }

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

1 Comment

Actually it works for all events.Sorry for my mistake. Actually I have dropdown and when I click on some item in dropdown I then press some key event is not called.
0

Yes. If you look at the angular examples for directives there is a drag/drop example which nests event bindings, namely mouseup, mousedown and mousemove events.

The bindings will happen in the expected order; in your case, keydown will not be bound until the mousedown event has been triggered.

Edit: you should be using .on() instead of .bind(), which is the newer and better syntax (see here).

2 Comments

Actually I have dropdown and when I click on some item in dropdown I then press some key event is not called
Are you sure you keydown event is being triggered correctly? You may want to apply the keydown to $document, although I'm not sure because I don't know what your element is.
0
// Create a function and call in even handlers.
app.directive('testDirective',function(){
   return{
    restrict:'A',
    link:function(scope, element, attrs) {

        element.bind('mousedown', logToConsole);
            element.bind('keydown', logToConsole);
        function logToConsole() {
           console.log('pressed');
        }
      }
     };
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.