AngularJS ng-click fires twice

后端 未结 18 1736
死守一世寂寞
死守一世寂寞 2020-12-03 07:10

I am using ng-click and it fires twice when I apply it to SPAN tag.

HTML

相关标签:
18条回答
  • 2020-12-03 07:36

    I have handled it by following code

    HTML :

    <div>
        <ui>
            <li>
                <button class="Button" ng-disabled="self.desableSubmitButton" ng- 
                click="self.SubmitClick($event)">Submit</button>
            </li>
        </ui> 
    </div>
    

    Angular 1.0 Controller :

    _self.SubmitClick = function(event){   
         _self.desableSubmitButton = true; //disable submit button
         event.preventDefault();
         event.stopPropagation();
    
         setTimeout(funtion() {
           _self.desableSubmitButton = false; //enable submit button after timeout
               if(_self.$scope.$$phase != '$apply' || _self.$scope.$$phase != '$digest'){
                 _self.$scope.$digest();
                 }
          }, 1000);//other Code logic
    }
    
    0 讨论(0)
  • 2020-12-03 07:37

    You might have a ng-click inside a form container using a ng-submit. In that case, add type="button" to all your using ng-click.

    0 讨论(0)
  • 2020-12-03 07:38

    I'm a bit of a dummy and had this:

    <li data-shape="amethyst" ng-click="toggleGem('amethyst')">
        <label></label>
        <i class="amethyst"></i>Amethyst
        <input type="checkbox" name="gem_type" id="gem-amethyst" value="amethyst" />
    </li>
    

    The click event was triggering twice. I moved the ng-click to the label element and it's working as expected.

    <li data-shape="amethyst">
        <label ng-click="toggleGem('amethyst')"></label>
        <i class="amethyst"></i>Amethyst
        <input type="checkbox" name="gem_type" id="gem-amethyst" value="amethyst" />
    </li>
    
    0 讨论(0)
  • 2020-12-03 07:43

    This situation may be caused by lacking the ngTouch in Angular.

    Event if the ngTouch is loaded, the bug in ngTouch and ngClick before Angular 1.5.0 may occur. It results from the ngClick being triggered by pointerup and mouseUp in Chrome for Desktop on device toolbar or mobile device.

    0 讨论(0)
  • 2020-12-03 07:45

    I don't know what was the reason this happened, but I had to use event.stopPropagation(); inner my JavaScript function.

    HTML

    <button class="button" ng-click="save($event)">Save</button>
    

    JAVASCRIPT

    function save(event) {
        event.stopPropagation();
    }
    
    0 讨论(0)
  • 2020-12-03 07:48

    elements wrapped one another, and this can cause trigger event twice or more.

    So i used a simple CSS trick for this solution :

    .off{
       pointer-events:none;
    }
    

    and apply it to an element correspond to click event.

    0 讨论(0)
提交回复
热议问题