简体   繁体   English

将单击事件绑定到角度链接器中的元素和子元素

[英]bind click event to element and children in angular linker

I have a directive which is basically a big table. 我有一条指令,基本上是一张大桌子。 In some of the cells in the table, I have divs with some content. 在表格的某些单元格中,我有一些内容的div。 Whenever a div is clicked I would like to do something (exemplified by the console.log("clicked") in my code below). 每当单击div时,我console.log("clicked")做某事(在下面的代码中以console.log("clicked")为例)。

The thing is that the div contains other html-elements as well, and if one of the descendant html-elements are clicked nothing happens. 事实是div也包含其他html元素,如果单击后代html元素之一,则不会发生任何事情。 So I would like to do something both when the parent div is clicked and when any descendant elements are clicked. 因此,我想在单击父div以及单击任何后代元素时都进行操作。

The following does something when the div is clicked but not when any descendant is clicked: 单击div时,以下操作会执行某些操作,但单击任何后代时,则不会执行以下操作:

link: function(scope, element) {
  element.on("click", function(e) {
    if (e.target.className.match('myclass')) 
       {
         console.log("Clicked!");
       }
    });
   }

How do I make sure the above happens when clicking the div AND any element inside the element with "myclass"? 单击div以及元素中带有“ myclass”的任何元素时,如何确保上述情况发生?

What you need in your event is 您在活动中需要的是

if (e.target.className.match('myclass') || $(e.target).closest('.myclass')) {
      alert("Clicked!");
    }

the function closest() allows you to search in the parents. 函数closest()允许您在父母中进行搜索。

(I assume you have jQuery in your project because is part of the tags) (我假设您的项目中有jQuery,因为它是标签的一部分)

Having said that, I strongly discourage you to mix jQuery and AngularJs unless is necessary. 话虽如此,除非有必要,否则我强烈建议您不要混合使用jQuery和AngularJs。 You could achieve similar functionality without using jQuery at all in your project in most cases. 在大多数情况下,您无需在项目中完全使用jQuery就可以实现类似的功能。

I believe you could get the same functionality if in your template for each div you just use ng-click="someFunction()" - it will fire when clicked from children elements 我相信,如果您在每个div的模板中仅使用ng-click="someFunction()" ,则可以获得相同的功能-当从子元素中单击时,它将触发

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM