AngularJS Click on TouchStart

benshope picture benshope · Jul 14, 2014 · Viewed 10.1k times · Source

Angular Touch ngTouch causes the click to occur on touch release.

Is there a way to make the click happen on touch start?

The fast-click directive below seems to do what I want on touchscreens, but it doesn't work with mouse clicks.

myApp.directive('fastClick', ['$parse', function ($parse) {
    return function (scope, element, attr) {
      var fn = $parse(attr['fastClick']);
      var initX, initY, endX, endY;
      var elem = element;

      elem.bind('touchstart', function (event) {
          event.preventDefault();
          initX = endX = event.touches[0].clientX;
          initY = endY = event.touches[0].clientY;
          scope.$apply(function () { fn(scope, { $event: event }); });
      });
    };
  }
]);

Answer

tymeJV picture tymeJV · Jul 14, 2014

Add click to the touchstart event - event.preventDefault() will cancel the event from happening twice:

elem.bind('touchstart click', function (event) {

A quick fastclick code that I use in one app is:

app.directive("ngMobileClick", [function () {
    return function (scope, elem, attrs) {
        elem.bind("touchstart click", function (e) {
            e.preventDefault();
            e.stopPropagation();

            scope.$apply(attrs["ngMobileClick"]);
        });
    }
}])

And use like: ng-mobile-click="myScopeFunction()"