简体   繁体   中英

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. Whenever a div is clicked I would like to do something (exemplified by the console.log("clicked") in my code below).

The thing is that the div contains other html-elements as well, and if one of the descendant html-elements are clicked nothing happens. So I would like to do something both when the parent div is clicked and when any descendant elements are clicked.

The following does something when the div is clicked but not when any descendant is clicked:

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"?

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.

(I assume you have jQuery in your project because is part of the tags)

Having said that, I strongly discourage you to mix jQuery and AngularJs unless is necessary. You could achieve similar functionality without using jQuery at all in your project in most cases.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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