在Angularjs中检测鼠标按下事件

6

我知道如何检测被点击的指令上的mousedown事件。然而,当鼠标在我的指令/元素之外按下时,我的指令也需要变为未聚焦或取消选择。我该怎么做?

1个回答

9
在指令中创建一个链接函数,将mousedown事件处理程序绑定在文档上。然后,在指令元素本身上绑定另一个mousedown事件。后者处理程序还应调用event.stopPropagation()来防止事件冒泡到文档级别:
link: function(scope, elem, attrs){
  angular.element(document).bind('mousedown', function(){
    console.log('clicked on document');
  });

  elem.bind('mousedown', function(e){
    e.stopPropagation();
    console.log('clicked on directive');
  });
}

可运行的 Plunker


这个会自动 $apply() 吗? - Dr.Knowitall

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接