Prevent swipe from triggering ng-click handler

巧了我就是萌 提交于 2019-12-03 02:24:46
Jennie Ji

I also met this situation and I finally found a tricky way to do that.
The $event.stopPropagation() mentioned somewhere only works in ngClick. Even writing a custom swipe directive by $swipe with event.stopPropagation() cannot prevent ngClick... So...

$swipe service will trigger both 'touch' and 'mouse' events by default. So does ngSwipeLeft and ngSwipeRight directives.
So when you do the swipe, it will trigger events by the following order:

  1. touchStart
  2. touchMove
  3. touchEnd
  4. mouseDown
  5. mouseUp
  6. click

I tested by mouse drag not touch directly, but my app will run on a touch screen on PC, and the swipe on this touch screen is emulating mouse drag. So the event type of $swipe service 'end' event in my app is 'mouseup'.
Then you can use a flag to do something like this:

<div ng-swipe-left="swipeFunc(); swiping=true;" ng-click="swiping ? ( swiping = false ) : clickFunc();">
   ...
</div>

or

<div ng-swipe-left="swipeFunc(); swiping=true;" ng-mouseup="clickFunc();" ng-click="swiping=false;">
  ...
</div>    

with clickFunc() like following:

$scope.clickFunc = function() {
   if( $scope.swiping ) { return; }
   // do something
}

This works for me. I hope this is also useful for you.

user3805000

I'm having this same problem right now as well, and indeed only on a desktop browser. I thought that preventDefault() or stopImmediatePropagation() would do the trick but no. However, I did find a solution for it though. Try this:

angular.module('app', [])
.directive('noSwipeClick', function () {
    return function(scope, elm) {
        var el = angular.element(elm);
        el.bind('click', function(e) {
          if(scope.swipe.swiping === true) {
            e.stopPropagation();
            e.preventDefault();
          }
        });
    };
});

And in your HTML:

<div class="list-item">
  <span>{{item.Name}}</span>
  <div ng-class="{true: 'is-visible', false: ''}[item.Id === swipeDeleteItemId]">
    <div no-swipe-click class="delete-item-swipe-button" 
     ng-mousedown="$event.stopPropagation();" 
     ng-click="$event.stopPropagation();">Delete</div>
  </div>
</div>

Don't forget to assign $scope.swipe.swiping = true in your controller when actually swiping and setting it to false when done

I was finally able to set up my development environment to allow me to test my application on an actual mobile device. I'm not noticing this behavior any longer - apparently a click and drag doesn't necessarily behave identically to a real swipe on a mobile device.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!