Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  81] [ 1]  / answers: 1 / hits: 35845  / 11 Years ago, thu, december 19, 2013, 12:00:00

Given the following code using angular.js



Plunkr here: http://plnkr.co/edit/i4MAzs



HTML:



<form name=myForm ng-controller=Ctrl>
Try clicking on the labels. <br/>
<label>
Value1: <input type=checkbox ng-checked='value1' ng-click='toggleValue1()'>
</label> <br/>
<label ng-click='toggleValue2()'>
Value2: <input type=checkbox ng-checked=value2>
</label> <br/>
<tt>value1 = {{value1}}</tt><br/>
<tt>value2 = {{value2}}</tt><br/>
<tt>fire_count = {{fire_count}}</tt>
</form>


Javascript:



angular.module('App', []);

function Ctrl($scope) {
$scope.value1 = true;
$scope.value2 = 'YES'
$scope.fire_count = 0;

$scope.toggleValue1 = function(){
$scope.value1 = !$scope.value1;
$scope.fire_count++;
console.log(Clicked!);
}

$scope.toggleValue2 = function(){
$scope.value2 = !$scope.value2;
$scope.fire_count++;
console.log(Clicked!);
}
}


The click event will fire twice when you click on the 'Value2' label. This only happens when ng-click is attached to the label. When it's attached to the input element everything works as expected.



Can someone explain what's going on?


More From » angularjs

 Answers
4

Take a look at this answer:



https://stackoverflow.com/a/17185362/3093703



Also, I've edited your plnkr to show the event target:



http://plnkr.co/edit/73aslwHnwVcTd2fxSJ0f?p=preview



Both the input and label elements are receiving the event.



To avoid this, you can check the tag name of the event target before performing any action.



Edit



As to why this is:
the label is actually tied to the input element in a way the div's or other elements would not be. The input is called the label's labeled control.



When you trigger an action on a label, that action is also run on the labeled control:




For example, on platforms where clicking a checkbox label checks the checkbox, clicking the label in the following snippet could trigger the user agent to run synthetic click activation steps on the input element, as if the element itself had been triggered by the user



[#73650] Wednesday, December 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
abagail

Total Points: 528
Total Questions: 109
Total Answers: 101

Location: Western Sahara
Member since Mon, May 3, 2021
3 Years ago
;