ng-change in a checkbox fired more than one time, because an ng-click over it
Asked Answered
D

2

7

As a code is better than 1000 words, I've created a plunker in order to show my problem: http://bit.ly/1uiR2wy

Given the specific DOM element, thing is that I have an input checkbox with an ng-change, I want to add an ng-click to the li that wraps it in order to be able to click in the whole area. This new ng-click makes the method in the ng-change to happens twice. And is even worse for an SPAN DESCRIPTION 2 that is happening 3 times.

<li class="odd" ng-click="changeToggleModel($event)">
  <span class="overcomeDescription ellipsis-overflow">span description</span>
  <label>      
    <span>SPAN DESCRIPTION 2</span>
    <input type="checkbox" ng-change="toggleSelection($event)" ng-model="isSelected">
  </label>
</li>

I've tried with stopPropagation and it seems that it doesn't solve the issue. Any ideas about it? If you check the plunker and open the console you'll see the issue perfectly.

Thanks in advance to everyone

Durra answered 16/11, 2014 at 22:9 Comment(0)
M
13

You need to stop event propagation on label level. Try this:

<label ng-click="$event.stopPropagation()" ...>

Demo: http://plnkr.co/edit/AjD9GlA3zjxABix6hegg?p=preview

The reason why it happens is that the label (connected to corresponding checkbox) sort of generates one more click event in order to pass click to the input. This click event causes described strange issues, because it still bubbles like normal event (well it is normal event), and hence is detected by ngClick directives.

Melanoid answered 16/11, 2014 at 22:14 Comment(1)
For me, there was no label as the checkbox was inside a table column. Hence, i added ng-click on <td> tag.Wu
C
1

Late to the party but encountered the same issue- it seems like AngularJS propagates the click event separately and explicitly. Instead of stopping propagation on the label, you can catch it on the input explicitly:

    <input 
      type="checkbox"
      ng-click="$event.stopPropagation()"
      ng-change="toggleSelection($event)"
      ng-model="isSelected"
    >
Copybook answered 8/5, 2017 at 20:44 Comment(1)
This seems to interfere with the checkbox's ng-change function, at least that's what I got.Trevortrevorr

© 2022 - 2024 — McMap. All rights reserved.