2 * @license AngularJS v1.4.3
3 * (c) 2010-2015 Google, Inc. http://angularjs.org
6 (function(window, angular, undefined) {'use strict';
15 * The `ngTouch` module provides touch events and other helpers for touch-enabled devices.
16 * The implementation is based on jQuery Mobile touch event handling
17 * ([jquerymobile.com](http://jquerymobile.com/)).
20 * See {@link ngTouch.$swipe `$swipe`} for usage.
22 * <div doc-module-components="ngTouch"></div>
26 // define ngTouch module
28 var ngTouch = angular.module('ngTouch', []);
30 function nodeName_(element) {
31 return angular.lowercase(element.nodeName || (element[0] && element[0].nodeName));
34 /* global ngTouch: false */
41 * The `$swipe` service is a service that abstracts the messier details of hold-and-drag swipe
42 * behavior, to make implementing swipe-related directives more convenient.
44 * Requires the {@link ngTouch `ngTouch`} module to be installed.
46 * `$swipe` is used by the `ngSwipeLeft` and `ngSwipeRight` directives in `ngTouch`, and by
47 * `ngCarousel` in a separate component.
50 * The `$swipe` service is an object with a single method: `bind`. `bind` takes an element
51 * which is to be watched for swipes, and an object with four handler functions. See the
52 * documentation for `bind` below.
55 ngTouch.factory('$swipe', [function() {
56 // The total distance in any direction before we make the call on swipe vs. scroll.
57 var MOVE_BUFFER_RADIUS = 10;
59 var POINTER_EVENTS = {
73 function getCoordinates(event) {
74 var originalEvent = event.originalEvent || event;
75 var touches = originalEvent.touches && originalEvent.touches.length ? originalEvent.touches : [originalEvent];
76 var e = (originalEvent.changedTouches && originalEvent.changedTouches[0]) || touches[0];
84 function getEvents(pointerTypes, eventType) {
86 angular.forEach(pointerTypes, function(pointerType) {
87 var eventName = POINTER_EVENTS[pointerType][eventType];
101 * The main method of `$swipe`. It takes an element to be watched for swipe motions, and an
102 * object containing event handlers.
103 * The pointer types that should be used can be specified via the optional
104 * third argument, which is an array of strings `'mouse'` and `'touch'`. By default,
105 * `$swipe` will listen for `mouse` and `touch` events.
107 * The four events are `start`, `move`, `end`, and `cancel`. `start`, `move`, and `end`
108 * receive as a parameter a coordinates object of the form `{ x: 150, y: 310 }` and the raw
109 * `event`. `cancel` receives the raw `event` as its single parameter.
111 * `start` is called on either `mousedown` or `touchstart`. After this event, `$swipe` is
112 * watching for `touchmove` or `mousemove` events. These events are ignored until the total
113 * distance moved in either dimension exceeds a small threshold.
115 * Once this threshold is exceeded, either the horizontal or vertical delta is greater.
116 * - If the horizontal distance is greater, this is a swipe and `move` and `end` events follow.
117 * - If the vertical distance is greater, this is a scroll, and we let the browser take over.
118 * A `cancel` event is sent.
120 * `move` is called on `mousemove` and `touchmove` after the above logic has determined that
121 * a swipe is in progress.
123 * `end` is called when a swipe is successfully completed with a `touchend` or `mouseup`.
125 * `cancel` is called either on a `touchcancel` from the browser, or when we begin scrolling
126 * as described above.
129 bind: function(element, eventHandlers, pointerTypes) {
130 // Absolute total movement, used to control swipe vs. scroll.
132 // Coordinates of the start position.
134 // Last event's position.
136 // Whether a swipe is active.
139 pointerTypes = pointerTypes || ['mouse', 'touch'];
140 element.on(getEvents(pointerTypes, 'start'), function(event) {
141 startCoords = getCoordinates(event);
145 lastPos = startCoords;
146 eventHandlers['start'] && eventHandlers['start'](startCoords, event);
148 var events = getEvents(pointerTypes, 'cancel');
150 element.on(events, function(event) {
152 eventHandlers['cancel'] && eventHandlers['cancel'](event);
156 element.on(getEvents(pointerTypes, 'move'), function(event) {
159 // Android will send a touchcancel if it thinks we're starting to scroll.
160 // So when the total distance (+ or - or both) exceeds 10px in either direction,
162 // - On totalX > totalY, we send preventDefault() and treat this as a swipe.
163 // - On totalY > totalX, we let the browser handle it as a scroll.
165 if (!startCoords) return;
166 var coords = getCoordinates(event);
168 totalX += Math.abs(coords.x - lastPos.x);
169 totalY += Math.abs(coords.y - lastPos.y);
173 if (totalX < MOVE_BUFFER_RADIUS && totalY < MOVE_BUFFER_RADIUS) {
177 // One of totalX or totalY has exceeded the buffer, so decide on swipe vs. scroll.
178 if (totalY > totalX) {
179 // Allow native scrolling to take over.
181 eventHandlers['cancel'] && eventHandlers['cancel'](event);
184 // Prevent the browser from scrolling.
185 event.preventDefault();
186 eventHandlers['move'] && eventHandlers['move'](coords, event);
190 element.on(getEvents(pointerTypes, 'end'), function(event) {
193 eventHandlers['end'] && eventHandlers['end'](getCoordinates(event), event);
199 /* global ngTouch: false,
208 * A more powerful replacement for the default ngClick designed to be used on touchscreen
209 * devices. Most mobile browsers wait about 300ms after a tap-and-release before sending
210 * the click event. This version handles them immediately, and then prevents the
211 * following click event from propagating.
213 * Requires the {@link ngTouch `ngTouch`} module to be installed.
215 * This directive can fall back to using an ordinary click event, and so works on desktop
216 * browsers as well as mobile.
218 * This directive also sets the CSS class `ng-click-active` while the element is being held
219 * down (by a mouse click or touch) so you can restyle the depressed element if you wish.
222 * @param {expression} ngClick {@link guide/expression Expression} to evaluate
223 * upon tap. (Event object is available as `$event`)
226 <example module="ngClickExample" deps="angular-touch.js">
227 <file name="index.html">
228 <button ng-click="count = count + 1" ng-init="count=0">
233 <file name="script.js">
234 angular.module('ngClickExample', ['ngTouch']);
239 ngTouch.config(['$provide', function($provide) {
240 $provide.decorator('ngClickDirective', ['$delegate', function($delegate) {
241 // drop the default ngClick directive
247 ngTouch.directive('ngClick', ['$parse', '$timeout', '$rootElement',
248 function($parse, $timeout, $rootElement) {
249 var TAP_DURATION = 750; // Shorter than 750ms is a tap, longer is a taphold or drag.
250 var MOVE_TOLERANCE = 12; // 12px seems to work in most mobile browsers.
251 var PREVENT_DURATION = 2500; // 2.5 seconds maximum from preventGhostClick call to click
252 var CLICKBUSTER_THRESHOLD = 25; // 25 pixels in any dimension is the limit for busting clicks.
254 var ACTIVE_CLASS_NAME = 'ng-click-active';
255 var lastPreventedTime;
256 var touchCoordinates;
257 var lastLabelClickCoordinates;
260 // TAP EVENTS AND GHOST CLICKS
263 // Mobile browsers detect a tap, then wait a moment (usually ~300ms) to see if you're
264 // double-tapping, and then fire a click event.
266 // This delay sucks and makes mobile apps feel unresponsive.
267 // So we detect touchstart, touchcancel and touchend ourselves and determine when
268 // the user has tapped on something.
270 // What happens when the browser then generates a click event?
271 // The browser, of course, also detects the tap and fires a click after a delay. This results in
272 // tapping/clicking twice. We do "clickbusting" to prevent it.
275 // We attach global touchstart and click handlers, that run during the capture (early) phase.
276 // So the sequence for a tap is:
277 // - global touchstart: Sets an "allowable region" at the point touched.
278 // - element's touchstart: Starts a touch
279 // (- touchcancel ends the touch, no click follows)
280 // - element's touchend: Determines if the tap is valid (didn't move too far away, didn't hold
281 // too long) and fires the user's tap handler. The touchend also calls preventGhostClick().
282 // - preventGhostClick() removes the allowable region the global touchstart created.
283 // - The browser generates a click event.
284 // - The global click handler catches the click, and checks whether it was in an allowable region.
285 // - If preventGhostClick was called, the region will have been removed, the click is busted.
286 // - If the region is still there, the click proceeds normally. Therefore clicks on links and
287 // other elements without ngTap on them work normally.
289 // This is an ugly, terrible hack!
290 // Yeah, tell me about it. The alternatives are using the slow click events, or making our users
291 // deal with the ghost clicks, so I consider this the least of evils. Fortunately Angular
292 // encapsulates this ugly logic away from the user.
294 // Why not just put click handlers on the element?
295 // We do that too, just to be sure. If the tap event caused the DOM to change,
296 // it is possible another element is now in that position. To take account for these possibly
297 // distinct elements, the handlers are global and care only about coordinates.
299 // Checks if the coordinates are close enough to be within the region.
300 function hit(x1, y1, x2, y2) {
301 return Math.abs(x1 - x2) < CLICKBUSTER_THRESHOLD && Math.abs(y1 - y2) < CLICKBUSTER_THRESHOLD;
304 // Checks a list of allowable regions against a click location.
305 // Returns true if the click should be allowed.
306 // Splices out the allowable region from the list after it has been used.
307 function checkAllowableRegions(touchCoordinates, x, y) {
308 for (var i = 0; i < touchCoordinates.length; i += 2) {
309 if (hit(touchCoordinates[i], touchCoordinates[i + 1], x, y)) {
310 touchCoordinates.splice(i, i + 2);
311 return true; // allowable region
314 return false; // No allowable region; bust it.
317 // Global click handler that prevents the click if it's in a bustable zone and preventGhostClick
318 // was called recently.
319 function onClick(event) {
320 if (Date.now() - lastPreventedTime > PREVENT_DURATION) {
324 var touches = event.touches && event.touches.length ? event.touches : [event];
325 var x = touches[0].clientX;
326 var y = touches[0].clientY;
327 // Work around desktop Webkit quirk where clicking a label will fire two clicks (on the label
328 // and on the input element). Depending on the exact browser, this second click we don't want
329 // to bust has either (0,0), negative coordinates, or coordinates equal to triggering label
331 if (x < 1 && y < 1) {
334 if (lastLabelClickCoordinates &&
335 lastLabelClickCoordinates[0] === x && lastLabelClickCoordinates[1] === y) {
336 return; // input click triggered by label click
338 // reset label click coordinates on first subsequent click
339 if (lastLabelClickCoordinates) {
340 lastLabelClickCoordinates = null;
342 // remember label click coordinates to prevent click busting of trigger click event on input
343 if (nodeName_(event.target) === 'label') {
344 lastLabelClickCoordinates = [x, y];
347 // Look for an allowable region containing this click.
348 // If we find one, that means it was created by touchstart and not removed by
349 // preventGhostClick, so we don't bust it.
350 if (checkAllowableRegions(touchCoordinates, x, y)) {
354 // If we didn't find an allowable region, bust the click.
355 event.stopPropagation();
356 event.preventDefault();
358 // Blur focused form elements
359 event.target && event.target.blur && event.target.blur();
363 // Global touchstart handler that creates an allowable region for a click event.
364 // This allowable region can be removed by preventGhostClick if we want to bust it.
365 function onTouchStart(event) {
366 var touches = event.touches && event.touches.length ? event.touches : [event];
367 var x = touches[0].clientX;
368 var y = touches[0].clientY;
369 touchCoordinates.push(x, y);
371 $timeout(function() {
372 // Remove the allowable region.
373 for (var i = 0; i < touchCoordinates.length; i += 2) {
374 if (touchCoordinates[i] == x && touchCoordinates[i + 1] == y) {
375 touchCoordinates.splice(i, i + 2);
379 }, PREVENT_DURATION, false);
382 // On the first call, attaches some event handlers. Then whenever it gets called, it creates a
383 // zone around the touchstart where clicks will get busted.
384 function preventGhostClick(x, y) {
385 if (!touchCoordinates) {
386 $rootElement[0].addEventListener('click', onClick, true);
387 $rootElement[0].addEventListener('touchstart', onTouchStart, true);
388 touchCoordinates = [];
391 lastPreventedTime = Date.now();
393 checkAllowableRegions(touchCoordinates, x, y);
396 // Actual linking function.
397 return function(scope, element, attr) {
398 var clickHandler = $parse(attr.ngClick),
400 tapElement, // Used to blur the element after a tap.
401 startTime, // Used to check if the tap was held too long.
405 function resetState() {
407 element.removeClass(ACTIVE_CLASS_NAME);
410 element.on('touchstart', function(event) {
412 tapElement = event.target ? event.target : event.srcElement; // IE uses srcElement.
413 // Hack for Safari, which can target text nodes instead of containers.
414 if (tapElement.nodeType == 3) {
415 tapElement = tapElement.parentNode;
418 element.addClass(ACTIVE_CLASS_NAME);
420 startTime = Date.now();
422 // Use jQuery originalEvent
423 var originalEvent = event.originalEvent || event;
424 var touches = originalEvent.touches && originalEvent.touches.length ? originalEvent.touches : [originalEvent];
426 touchStartX = e.clientX;
427 touchStartY = e.clientY;
430 element.on('touchcancel', function(event) {
434 element.on('touchend', function(event) {
435 var diff = Date.now() - startTime;
437 // Use jQuery originalEvent
438 var originalEvent = event.originalEvent || event;
439 var touches = (originalEvent.changedTouches && originalEvent.changedTouches.length) ?
440 originalEvent.changedTouches :
441 ((originalEvent.touches && originalEvent.touches.length) ? originalEvent.touches : [originalEvent]);
445 var dist = Math.sqrt(Math.pow(x - touchStartX, 2) + Math.pow(y - touchStartY, 2));
447 if (tapping && diff < TAP_DURATION && dist < MOVE_TOLERANCE) {
448 // Call preventGhostClick so the clickbuster will catch the corresponding click.
449 preventGhostClick(x, y);
451 // Blur the focused element (the button, probably) before firing the callback.
452 // This doesn't work perfectly on Android Chrome, but seems to work elsewhere.
453 // I couldn't get anything to work reliably on Android Chrome.
458 if (!angular.isDefined(attr.disabled) || attr.disabled === false) {
459 element.triggerHandler('click', [event]);
466 // Hack for iOS Safari's benefit. It goes searching for onclick handlers and is liable to click
467 // something else nearby.
468 element.onclick = function(event) { };
470 // Actual click handler.
471 // There are three different kinds of clicks, only two of which reach this point.
472 // - On desktop browsers without touch events, their clicks will always come here.
473 // - On mobile browsers, the simulated "fast" click will call this.
474 // - But the browser's follow-up slow click will be "busted" before it reaches this handler.
475 // Therefore it's safe to use this directive on both mobile and desktop.
476 element.on('click', function(event, touchend) {
477 scope.$apply(function() {
478 clickHandler(scope, {$event: (touchend || event)});
482 element.on('mousedown', function(event) {
483 element.addClass(ACTIVE_CLASS_NAME);
486 element.on('mousemove mouseup', function(event) {
487 element.removeClass(ACTIVE_CLASS_NAME);
493 /* global ngTouch: false */
500 * Specify custom behavior when an element is swiped to the left on a touchscreen device.
501 * A leftward swipe is a quick, right-to-left slide of the finger.
502 * Though ngSwipeLeft is designed for touch-based devices, it will work with a mouse click and drag
505 * To disable the mouse click and drag functionality, add `ng-swipe-disable-mouse` to
506 * the `ng-swipe-left` or `ng-swipe-right` DOM Element.
508 * Requires the {@link ngTouch `ngTouch`} module to be installed.
511 * @param {expression} ngSwipeLeft {@link guide/expression Expression} to evaluate
512 * upon left swipe. (Event object is available as `$event`)
515 <example module="ngSwipeLeftExample" deps="angular-touch.js">
516 <file name="index.html">
517 <div ng-show="!showActions" ng-swipe-left="showActions = true">
518 Some list content, like an email in the inbox
520 <div ng-show="showActions" ng-swipe-right="showActions = false">
521 <button ng-click="reply()">Reply</button>
522 <button ng-click="delete()">Delete</button>
525 <file name="script.js">
526 angular.module('ngSwipeLeftExample', ['ngTouch']);
536 * Specify custom behavior when an element is swiped to the right on a touchscreen device.
537 * A rightward swipe is a quick, left-to-right slide of the finger.
538 * Though ngSwipeRight is designed for touch-based devices, it will work with a mouse click and drag
541 * Requires the {@link ngTouch `ngTouch`} module to be installed.
544 * @param {expression} ngSwipeRight {@link guide/expression Expression} to evaluate
545 * upon right swipe. (Event object is available as `$event`)
548 <example module="ngSwipeRightExample" deps="angular-touch.js">
549 <file name="index.html">
550 <div ng-show="!showActions" ng-swipe-left="showActions = true">
551 Some list content, like an email in the inbox
553 <div ng-show="showActions" ng-swipe-right="showActions = false">
554 <button ng-click="reply()">Reply</button>
555 <button ng-click="delete()">Delete</button>
558 <file name="script.js">
559 angular.module('ngSwipeRightExample', ['ngTouch']);
564 function makeSwipeDirective(directiveName, direction, eventName) {
565 ngTouch.directive(directiveName, ['$parse', '$swipe', function($parse, $swipe) {
566 // The maximum vertical delta for a swipe should be less than 75px.
567 var MAX_VERTICAL_DISTANCE = 75;
568 // Vertical distance should not be more than a fraction of the horizontal distance.
569 var MAX_VERTICAL_RATIO = 0.3;
570 // At least a 30px lateral motion is necessary for a swipe.
571 var MIN_HORIZONTAL_DISTANCE = 30;
573 return function(scope, element, attr) {
574 var swipeHandler = $parse(attr[directiveName]);
576 var startCoords, valid;
578 function validSwipe(coords) {
579 // Check that it's within the coordinates.
580 // Absolute vertical distance must be within tolerances.
581 // Horizontal distance, we take the current X - the starting X.
582 // This is negative for leftward swipes and positive for rightward swipes.
583 // After multiplying by the direction (-1 for left, +1 for right), legal swipes
584 // (ie. same direction as the directive wants) will have a positive delta and
585 // illegal ones a negative delta.
586 // Therefore this delta must be positive, and larger than the minimum.
587 if (!startCoords) return false;
588 var deltaY = Math.abs(coords.y - startCoords.y);
589 var deltaX = (coords.x - startCoords.x) * direction;
590 return valid && // Short circuit for already-invalidated swipes.
591 deltaY < MAX_VERTICAL_DISTANCE &&
593 deltaX > MIN_HORIZONTAL_DISTANCE &&
594 deltaY / deltaX < MAX_VERTICAL_RATIO;
597 var pointerTypes = ['touch'];
598 if (!angular.isDefined(attr['ngSwipeDisableMouse'])) {
599 pointerTypes.push('mouse');
601 $swipe.bind(element, {
602 'start': function(coords, event) {
603 startCoords = coords;
606 'cancel': function(event) {
609 'end': function(coords, event) {
610 if (validSwipe(coords)) {
611 scope.$apply(function() {
612 element.triggerHandler(eventName);
613 swipeHandler(scope, {$event: event});
622 // Left is negative X-coordinate, right is positive.
623 makeSwipeDirective('ngSwipeLeft', -1, 'swipeleft');
624 makeSwipeDirective('ngSwipeRight', 1, 'swiperight');
628 })(window, window.angular);