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

5.4k views Asked by At

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

2

There are 2 answers

1
dfsq On BEST ANSWER

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.

1
mhriess On

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