How to prevent ng-click's triggering twice on label tag?

前端 未结 3 1761
谎友^
谎友^ 2021-01-12 12:34

Angular\'s ng-click gets triggered twice when I click label which has input inside in it. I\'ve tried $event.stopPropagation(); but didn\'t work. How do I solve

3条回答
  •  渐次进展
    2021-01-12 13:35

    Well thats because label is the parent or container for the checkbox, so the click handler is attached to the complete container in your case, thereby whenever either label or checkbox is clicked, event is triggered.


    Whats wrong with your approach:

    • Firstly never insert the input tags inside the label, thats not a good way to construct markup in html.In Angular.js this behaviour causes the click event to be triggered for both the tags. so to add a binding between input tag & label use the for attribute of label.
    • Using $event.stopPropagation() inside label actually stops all events from propagating/boiling to the top of the DOM from the label. this will not serve any purpose because the event would still propagate to the input with in the label.

    I hope you can visualise what i'm saying.

    What I have done:

    • Use for attribute to bind the input to the label & add a click event to prevent the default functionality.
    • Add the click handler to the respective input tag & not the label

    Live Demo @ JSFiddle

    This way you don't have to worry about any conflicts in event handling,also its neat way to maintain the HTML code :)

提交回复
热议问题