How to prevent double-clicking on a tag label?

Agnular ng-click triggers twice when I click on a label that has an input inside. I tried $event.stopPropagation(); but did not work, how to solve this :?

I also checked this question: Angular. Jj ng-click events on shortcuts fire twice

 <div class="list-group-item" ng-repeat="item in model.data"> <form role="form" name="selectForm" novalidate> <label ng-click="$event.stopPropagation(); updateSelected();"> <input type="checkbox" ng-model="chechkedSkins[item.id]" /> <span>{{item.name}}</span> </label> </form> </div> 
+6
source share
3 answers

Use ng-change="updateSelected"

Use this only in the input, as the change is triggered even if you click on the label.

+6
source

Good, because the label is the parent or container for the checkbox , so the click handler attaches to the full container in your case, so whenever the label or checkbox clicked, the event fires.


What is wrong with your approach:

  • Firstly, never insert input tags inside labels, this is not a good way to create markup in html. In Angular.js this triggers a click event for both tags. therefore, to add a binding between the input and label tags, use the for attribute of the label.
  • Using $event.stopPropagation() inside the label actually stops all events from spreading / boiling to the top of the DOM from the label. this will not serve any purpose, because the event will still propagate to the tagged input.

Hope you can visualize what I am saying.

What I've done:

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

    <label for="username" ng-click="$event.preventDefault();">Click me</label> <input type="text" id="username" ng-click="updateSelected();">

Live Demo @JSFiddle

This way, you don’t have to worry about any conflicts when handling events, nor about its neat way to support HTML code :)

+5
source

I am using the latest version of Angular Material 1.0.3 and still have this problem when clicking on shortcuts configured as buttons on Android. I have no problem with iOS or browser (cordova app). The following resolved this for me.

my html:

  <label class="btn btn-primary" ng-click="vm.goAbout()">About</label> 

my controller:

  vm.goAbout = debounceFn(function(){ //show dialog here, and now it only pops up once }, 250, false); 

Debounce function:

 function debounceFn(func, wait, immediate){ var timeout; var deferred = $q.defer(); return function() { var context = this, args = arguments; var later = function() { timeout = null; if(!immediate) { deferred.resolve(func.apply(context, args)); deferred = $q.defer(); } }; var callNow = immediate && !timeout; if ( timeout ) { $timeout.cancel(timeout); } timeout = $timeout(later, wait); if (callNow) { deferred.resolve(func.apply(context,args)); deferred = $q.defer(); } return deferred.promise; } } 
+1
source

All Articles