简体   繁体   中英

How to fastClick + AngularJS for iPad

There is a delay when clicking with ng-click on iPad with AngularJS I have the generate directive I need to write

my_app.directive 'touch', ->
  (scope, e, attr) ->
    e.fastClick (e) ->
      scope.$apply attr.fastClick

But it doesn't know what fastClick is even though I've included it in my application. I would think it needs to be created as a service and then injected into my directive, but how?

Just in case someone else finds this, who does not use coffee script, here is the conversion

 app.directive("ngTap", function() {
  return function($scope, $element, $attributes) {
    var tapped;
    tapped = false;
    $element.bind("click", function() {
      if (!tapped) {
        return $scope.$apply($attributes["ngTap"]);
      }
    });
    $element.bind("touchstart", function(event) {
      return tapped = true;
    });
    $element.bind("touchmove", function(event) {
      tapped = false;
      return event.stopImmediatePropagation();
    });
    return $element.bind("touchend", function() {
      if (tapped) {
        return $scope.$apply($attributes["ngTap"]);
      }
    });
  };
});

it's gfTop, becuase the sample is "good films" app. Feel free to change that to whatever you like.

Also note, that you have to change all your "ng-click"s to "gfTap"s.

UPDATED: to handle tap and click events.

It's pretty simple to implement your own tapping directive without an external library. I would advise that.

Goodfilms went over it in their blog post about their AngularJS mobile app: http://goodfil.ms/blog/posts/2012/08/13/angularjs-and-the-goodfilms-mobile-site-part-1/

Here's their tap code (also in Coffeescript), straight from the blog post:

app.directive 'gfTap', ->
  (scope, element, attrs) ->
    tapping = false
    element.bind 'touchstart', -> tapping = true
    element.bind 'touchmove', -> tapping = false
    element.bind 'touchend', -> scope.$apply(attrs['gfTap']) if tapping

AngularJS 1.1.5 ships with a built-in ng-click directive that handles touch events.

Docs: http://code.angularjs.org/1.1.5/docs/api/ngMobile.directive:ngClick

Source: https://github.com/angular/angular.js/blob/master/src/ngMobile/directive/ngClick.js

I strongly recommend against implementing a directive like this yourself - there are many edge cases that can break (ghost clicks, etc). Look at the code referenced above for more examples of edge cases that you'll need to handle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM