Ealon Ealon - 5 months ago 16
AngularJS Question

Clicking label triggers sliding animation twice

I cannot figure out that in this demo, why clicking label triggers sliding animation twice, while clicking check box triggers sliding animation once. Can someone explain this? Thanks!

I attach the code here.

<div ng-app="labelApp" ng-controller="labelCtrl">
<label ng-click="toggle()">
<input type="checkbox">Click to toggle slide</label>
<div id="myDiv">
Clicking check box triggers sliding animation once.
<br>
Clicking label triggers sliding animation twice.
</div>
</div>

angular.module("labelApp", [])
.controller("labelCtrl", function($scope) {
$scope.toggle = function() {
$("#myDiv").slideToggle();
}
});

Answer

When you click the label the event will tunnel down to the input where it will cause the checkbox to be checked and then it will bubble back up to the label again. So your handler on the label gets fired twice. The quick fix is to just put the handler on the input instead:

<label>
    <input ng-click="toggle()" type="checkbox">Click to toggle slide
</label>

But probably more appropriate would be to use ng-change:

<input ng-change="toggle()" ng-model="isChecked" type="checkbox">Click to toggle slide
Comments