如何使用Angular Directive捕获触摸事件

时间:2013-11-27 04:21:19

标签: angularjs touch

我希望能够捕捉到用户将手指移动到触摸设备上的一组DOM元素的事实。此示例在桌面浏览器上正常工作,但在移动Safari中查看时不会触发所有预期的事件。

Working Plunkr(演示移动游猎的问题): http://plnkr.co/edit/J8sfuJ9o6DorMSFlK9v2

HTML:

<body ng-controller="MainCtrl">
  <p>Hello {{name}}!  This works from a desktop browser but not from mobile Safari.  I would simply like to be able to drag my finger down, across all four letters, and have their events fire.  I thought that touchMove would work in place of mouseMove when running this Plunkr on iOS, but it doesn't.</p>  Current letter: {{currentLetter}}

    <div swipe-over="swipeOver()">A</div>
    <div swipe-over="swipeOver()">B</div>
    <div swipe-over="swipeOver()">C</div>
    <div swipe-over="swipeOver()">D</div>
</body>

使用Javascript:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $log) {
  $scope.name = 'World';
  $scope.currentLetter = "";

  $scope.swipeOver = function() {
    $log.info("In swipeOver");
  };
});

app.directive('swipeOver', function($log) {
  return {
    restrict: "A",
    scope: true,
    link: function(scope, element, attrs) {
      // For touch devices
      element.bind("touchmove", function() {
        scope.$apply(function(evt) {
          $log.info("in touchmove - " + element.text());

          scope.$parent.currentLetter = element.text();
        });
      });

      // For desktops
      element.bind("mousemove", function(evt, e2) {
        scope.$apply(function() {
            $log.info(evt);
            $log.info(e2);
            $log.info("in mousemove - " + element.text());

            scope.$parent.currentLetter = element.text();
        });
      });
    }
  };
});

我尝试过ng-touch库,但它不支持垂直触摸动作,令人惊讶。在这一点上,任何帮助都将受到大力赞赏。 。

2 个答案:

答案 0 :(得分:4)

目前这是touchmove的限制,我担心没有真正好的答案。

最佳解决方案是将touchmove绑定到父元素,然后计算当前触摸点下的子元素。它在jQuery上下文中得到了解答Crossing over to new elements during touchmove

您需要遍历父项上的每个子元素,并检查触摸点是否在其范围内。

答案 1 :(得分:-1)

使用Hammer.JS,这是我所知道的最好的。可以轻松修改Angular-Hammer以支持版本2.