在angular指令中组合两个事件处理程序

时间:2015-08-13 07:46:46

标签: javascript angularjs angularjs-directive

是否可以在angular指令的link函数中使用其中一个事件处理程序,如下所示:

  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 个答案:

答案 0 :(得分:2)

是的,在某些情况下,您需要嵌套事件函数,例如,如下所示,一旦触发父事件,嵌套事件将被绑定。例如,在mouseenter下面,单击元素

后将触发mouseleave
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")
            })

          })
        }

      }
    })

答案 1 :(得分:0)

是。如果你看一下angular examples for directives,就会有一个拖放事件绑定的拖放示例,即mouseup,mousedown和mousemove事件。

绑定将按预期顺序发生;在你的情况下,直到mousedown事件被触发才会绑定keydown。

编辑:您应该使用.on()而不是.bind(),这是更新更好的语法(see here)。

答案 2 :(得分: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');
        }
      }
     };
});