2 * @license AngularJS v1.4.10
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`.
49 * The `$swipe` service is an object with a single method: `bind`. `bind` takes an element
50 * which is to be watched for swipes, and an object with four handler functions. See the
51 * documentation for `bind` below.
54 ngTouch.factory('$swipe', [function() {
55 // The total distance in any direction before we make the call on swipe vs. scroll.
56 var MOVE_BUFFER_RADIUS = 10;
58 var POINTER_EVENTS = {
72 function getCoordinates(event) {
73 var originalEvent = event.originalEvent || event;
74 var touches = originalEvent.touches && originalEvent.touches.length ? originalEvent.touches : [originalEvent];
75 var e = (originalEvent.changedTouches && originalEvent.changedTouches[0]) || touches[0];
83 function getEvents(pointerTypes, eventType) {
85 angular.forEach(pointerTypes, function(pointerType) {
86 var eventName = POINTER_EVENTS[pointerType][eventType];
100 * The main method of `$swipe`. It takes an element to be watched for swipe motions, and an
101 * object containing event handlers.
102 * The pointer types that should be used can be specified via the optional
103 * third argument, which is an array of strings `'mouse'` and `'touch'`. By default,
104 * `$swipe` will listen for `mouse` and `touch` events.
106 * The four events are `start`, `move`, `end`, and `cancel`. `start`, `move`, and `end`
107 * receive as a parameter a coordinates object of the form `{ x: 150, y: 310 }` and the raw
108 * `event`. `cancel` receives the raw `event` as its single parameter.
110 * `start` is called on either `mousedown` or `touchstart`. After this event, `$swipe` is
111 * watching for `touchmove` or `mousemove` events. These events are ignored until the total
112 * distance moved in either dimension exceeds a small threshold.
114 * Once this threshold is exceeded, either the horizontal or vertical delta is greater.
115 * - If the horizontal distance is greater, this is a swipe and `move` and `end` events follow.
116 * - If the vertical distance is greater, this is a scroll, and we let the browser take over.
117 * A `cancel` event is sent.
119 * `move` is called on `mousemove` and `touchmove` after the above logic has determined that
120 * a swipe is in progress.
122 * `end` is called when a swipe is successfully completed with a `touchend` or `mouseup`.
124 * `cancel` is called either on a `touchcancel` from the browser, or when we begin scrolling
125 * as described above.
128 bind: function(element, eventHandlers, pointerTypes) {
129 // Absolute total movement, used to control swipe vs. scroll.
131 // Coordinates of the start position.
133 // Last event's position.
135 // Whether a swipe is active.
138 pointerTypes = pointerTypes || ['mouse', 'touch'];
139 element.on(getEvents(pointerTypes, 'start'), function(event) {
140 startCoords = getCoordinates(event);
144 lastPos = startCoords;
145 eventHandlers['start'] && eventHandlers['start'](startCoords, event);
147 var events = getEvents(pointerTypes, 'cancel');
149 element.on(events, function(event) {
151 eventHandlers['cancel'] && eventHandlers['cancel'](event);
155 element.on(getEvents(pointerTypes, 'move'), function(event) {
158 // Android will send a touchcancel if it thinks we're starting to scroll.
159 // So when the total distance (+ or - or both) exceeds 10px in either direction,
161 // - On totalX > totalY, we send preventDefault() and treat this as a swipe.
162 // - On totalY > totalX, we let the browser handle it as a scroll.
164 if (!startCoords) return;
165 var coords = getCoordinates(event);
167 totalX += Math.abs(coords.x - lastPos.x);
168 totalY += Math.abs(coords.y - lastPos.y);
172 if (totalX < MOVE_BUFFER_RADIUS && totalY < MOVE_BUFFER_RADIUS) {
176 // One of totalX or totalY has exceeded the buffer, so decide on swipe vs. scroll.
177 if (totalY > totalX) {
178 // Allow native scrolling to take over.
180 eventHandlers['cancel'] && eventHandlers['cancel'](event);
183 // Prevent the browser from scrolling.
184 event.preventDefault();
185 eventHandlers['move'] && eventHandlers['move'](coords, event);
189 element.on(getEvents(pointerTypes, 'end'), function(event) {
192 eventHandlers['end'] && eventHandlers['end'](getCoordinates(event), event);
198 /* global ngTouch: false,
207 * A more powerful replacement for the default ngClick designed to be used on touchscreen
208 * devices. Most mobile browsers wait about 300ms after a tap-and-release before sending
209 * the click event. This version handles them immediately, and then prevents the
210 * following click event from propagating.
212 * Requires the {@link ngTouch `ngTouch`} module to be installed.
214 * This directive can fall back to using an ordinary click event, and so works on desktop
215 * browsers as well as mobile.
217 * This directive also sets the CSS class `ng-click-active` while the element is being held
218 * down (by a mouse click or touch) so you can restyle the depressed element if you wish.
221 * @param {expression} ngClick {@link guide/expression Expression} to evaluate
222 * upon tap. (Event object is available as `$event`)
225 <example module="ngClickExample" deps="angular-touch.js">
226 <file name="index.html">
227 <button ng-click="count = count + 1" ng-init="count=0">
232 <file name="script.js">
233 angular.module('ngClickExample', ['ngTouch']);
238 ngTouch.config(['$provide', function($provide) {
239 $provide.decorator('ngClickDirective', ['$delegate', function($delegate) {
240 // drop the default ngClick directive
246 ngTouch.directive('ngClick', ['$parse', '$timeout', '$rootElement',
247 function($parse, $timeout, $rootElement) {
248 var TAP_DURATION = 750; // Shorter than 750ms is a tap, longer is a taphold or drag.
249 var MOVE_TOLERANCE = 12; // 12px seems to work in most mobile browsers.
250 var PREVENT_DURATION = 2500; // 2.5 seconds maximum from preventGhostClick call to click
251 var CLICKBUSTER_THRESHOLD = 25; // 25 pixels in any dimension is the limit for busting clicks.
253 var ACTIVE_CLASS_NAME = 'ng-click-active';
254 var lastPreventedTime;
255 var touchCoordinates;
256 var lastLabelClickCoordinates;
259 // TAP EVENTS AND GHOST CLICKS
262 // Mobile browsers detect a tap, then wait a moment (usually ~300ms) to see if you're
263 // double-tapping, and then fire a click event.
265 // This delay sucks and makes mobile apps feel unresponsive.
266 // So we detect touchstart, touchcancel and touchend ourselves and determine when
267 // the user has tapped on something.
269 // What happens when the browser then generates a click event?
270 // The browser, of course, also detects the tap and fires a click after a delay. This results in
271 // tapping/clicking twice. We do "clickbusting" to prevent it.
274 // We attach global touchstart and click handlers, that run during the capture (early) phase.
275 // So the sequence for a tap is:
276 // - global touchstart: Sets an "allowable region" at the point touched.
277 // - element's touchstart: Starts a touch
278 // (- touchcancel ends the touch, no click follows)
279 // - element's touchend: Determines if the tap is valid (didn't move too far away, didn't hold
280 // too long) and fires the user's tap handler. The touchend also calls preventGhostClick().
281 // - preventGhostClick() removes the allowable region the global touchstart created.
282 // - The browser generates a click event.
283 // - The global click handler catches the click, and checks whether it was in an allowable region.
284 // - If preventGhostClick was called, the region will have been removed, the click is busted.
285 // - If the region is still there, the click proceeds normally. Therefore clicks on links and
286 // other elements without ngTap on them work normally.
288 // This is an ugly, terrible hack!
289 // Yeah, tell me about it. The alternatives are using the slow click events, or making our users
290 // deal with the ghost clicks, so I consider this the least of evils. Fortunately Angular
291 // encapsulates this ugly logic away from the user.
293 // Why not just put click handlers on the element?
294 // We do that too, just to be sure. If the tap event caused the DOM to change,
295 // it is possible another element is now in that position. To take account for these possibly
296 // distinct elements, the handlers are global and care only about coordinates.
298 // Checks if the coordinates are close enough to be within the region.
299 function hit(x1, y1, x2, y2) {
300 return Math.abs(x1 - x2) < CLICKBUSTER_THRESHOLD && Math.abs(y1 - y2) < CLICKBUSTER_THRESHOLD;
303 // Checks a list of allowable regions against a click location.
304 // Returns true if the click should be allowed.
305 // Splices out the allowable region from the list after it has been used.
306 function checkAllowableRegions(touchCoordinates, x, y) {
307 for (var i = 0; i < touchCoordinates.length; i += 2) {
308 if (hit(touchCoordinates[i], touchCoordinates[i + 1], x, y)) {
309 touchCoordinates.splice(i, i + 2);
310 return true; // allowable region
313 return false; // No allowable region; bust it.
316 // Global click handler that prevents the click if it's in a bustable zone and preventGhostClick
317 // was called recently.
318 function onClick(event) {
319 if (Date.now() - lastPreventedTime > PREVENT_DURATION) {
323 var touches = event.touches && event.touches.length ? event.touches : [event];
324 var x = touches[0].clientX;
325 var y = touches[0].clientY;
326 // Work around desktop Webkit quirk where clicking a label will fire two clicks (on the label
327 // and on the input element). Depending on the exact browser, this second click we don't want
328 // to bust has either (0,0), negative coordinates, or coordinates equal to triggering label
330 if (x < 1 && y < 1) {
333 if (lastLabelClickCoordinates &&
334 lastLabelClickCoordinates[0] === x && lastLabelClickCoordinates[1] === y) {
335 return; // input click triggered by label click
337 // reset label click coordinates on first subsequent click
338 if (lastLabelClickCoordinates) {
339 lastLabelClickCoordinates = null;
341 // remember label click coordinates to prevent click busting of trigger click event on input
342 if (nodeName_(event.target) === 'label') {
343 lastLabelClickCoordinates = [x, y];
346 // Look for an allowable region containing this click.
347 // If we find one, that means it was created by touchstart and not removed by
348 // preventGhostClick, so we don't bust it.
349 if (checkAllowableRegions(touchCoordinates, x, y)) {
353 // If we didn't find an allowable region, bust the click.
354 event.stopPropagation();
355 event.preventDefault();
357 // Blur focused form elements
358 event.target && event.target.blur && event.target.blur();
362 // Global touchstart handler that creates an allowable region for a click event.
363 // This allowable region can be removed by preventGhostClick if we want to bust it.
364 function onTouchStart(event) {
365 var touches = event.touches && event.touches.length ? event.touches : [event];
366 var x = touches[0].clientX;
367 var y = touches[0].clientY;
368 touchCoordinates.push(x, y);
370 $timeout(function() {
371 // Remove the allowable region.
372 for (var i = 0; i < touchCoordinates.length; i += 2) {
373 if (touchCoordinates[i] == x && touchCoordinates[i + 1] == y) {
374 touchCoordinates.splice(i, i + 2);
378 }, PREVENT_DURATION, false);
381 // On the first call, attaches some event handlers. Then whenever it gets called, it creates a
382 // zone around the touchstart where clicks will get busted.
383 function preventGhostClick(x, y) {
384 if (!touchCoordinates) {
385 $rootElement[0].addEventListener('click', onClick, true);
386 $rootElement[0].addEventListener('touchstart', onTouchStart, true);
387 touchCoordinates = [];
390 lastPreventedTime = Date.now();
392 checkAllowableRegions(touchCoordinates, x, y);
395 // Actual linking function.
396 return function(scope, element, attr) {
397 var clickHandler = $parse(attr.ngClick),
399 tapElement, // Used to blur the element after a tap.
400 startTime, // Used to check if the tap was held too long.
404 function resetState() {
406 element.removeClass(ACTIVE_CLASS_NAME);
409 element.on('touchstart', function(event) {
411 tapElement = event.target ? event.target : event.srcElement; // IE uses srcElement.
412 // Hack for Safari, which can target text nodes instead of containers.
413 if (tapElement.nodeType == 3) {
414 tapElement = tapElement.parentNode;
417 element.addClass(ACTIVE_CLASS_NAME);
419 startTime = Date.now();
421 // Use jQuery originalEvent
422 var originalEvent = event.originalEvent || event;
423 var touches = originalEvent.touches && originalEvent.touches.length ? originalEvent.touches : [originalEvent];
425 touchStartX = e.clientX;
426 touchStartY = e.clientY;
429 element.on('touchcancel', function(event) {
433 element.on('touchend', function(event) {
434 var diff = Date.now() - startTime;
436 // Use jQuery originalEvent
437 var originalEvent = event.originalEvent || event;
438 var touches = (originalEvent.changedTouches && originalEvent.changedTouches.length) ?
439 originalEvent.changedTouches :
440 ((originalEvent.touches && originalEvent.touches.length) ? originalEvent.touches : [originalEvent]);
444 var dist = Math.sqrt(Math.pow(x - touchStartX, 2) + Math.pow(y - touchStartY, 2));
446 if (tapping && diff < TAP_DURATION && dist < MOVE_TOLERANCE) {
447 // Call preventGhostClick so the clickbuster will catch the corresponding click.
448 preventGhostClick(x, y);
450 // Blur the focused element (the button, probably) before firing the callback.
451 // This doesn't work perfectly on Android Chrome, but seems to work elsewhere.
452 // I couldn't get anything to work reliably on Android Chrome.
457 if (!angular.isDefined(attr.disabled) || attr.disabled === false) {
458 element.triggerHandler('click', [event]);
465 // Hack for iOS Safari's benefit. It goes searching for onclick handlers and is liable to click
466 // something else nearby.
467 element.onclick = function(event) { };
469 // Actual click handler.
470 // There are three different kinds of clicks, only two of which reach this point.
471 // - On desktop browsers without touch events, their clicks will always come here.
472 // - On mobile browsers, the simulated "fast" click will call this.
473 // - But the browser's follow-up slow click will be "busted" before it reaches this handler.
474 // Therefore it's safe to use this directive on both mobile and desktop.
475 element.on('click', function(event, touchend) {
476 scope.$apply(function() {
477 clickHandler(scope, {$event: (touchend || event)});
481 element.on('mousedown', function(event) {
482 element.addClass(ACTIVE_CLASS_NAME);
485 element.on('mousemove mouseup', function(event) {
486 element.removeClass(ACTIVE_CLASS_NAME);
492 /* global ngTouch: false */
499 * Specify custom behavior when an element is swiped to the left on a touchscreen device.
500 * A leftward swipe is a quick, right-to-left slide of the finger.
501 * Though ngSwipeLeft is designed for touch-based devices, it will work with a mouse click and drag
504 * To disable the mouse click and drag functionality, add `ng-swipe-disable-mouse` to
505 * the `ng-swipe-left` or `ng-swipe-right` DOM Element.
507 * Requires the {@link ngTouch `ngTouch`} module to be installed.
510 * @param {expression} ngSwipeLeft {@link guide/expression Expression} to evaluate
511 * upon left swipe. (Event object is available as `$event`)
514 <example module="ngSwipeLeftExample" deps="angular-touch.js">
515 <file name="index.html">
516 <div ng-show="!showActions" ng-swipe-left="showActions = true">
517 Some list content, like an email in the inbox
519 <div ng-show="showActions" ng-swipe-right="showActions = false">
520 <button ng-click="reply()">Reply</button>
521 <button ng-click="delete()">Delete</button>
524 <file name="script.js">
525 angular.module('ngSwipeLeftExample', ['ngTouch']);
535 * Specify custom behavior when an element is swiped to the right on a touchscreen device.
536 * A rightward swipe is a quick, left-to-right slide of the finger.
537 * Though ngSwipeRight is designed for touch-based devices, it will work with a mouse click and drag
540 * Requires the {@link ngTouch `ngTouch`} module to be installed.
543 * @param {expression} ngSwipeRight {@link guide/expression Expression} to evaluate
544 * upon right swipe. (Event object is available as `$event`)
547 <example module="ngSwipeRightExample" deps="angular-touch.js">
548 <file name="index.html">
549 <div ng-show="!showActions" ng-swipe-left="showActions = true">
550 Some list content, like an email in the inbox
552 <div ng-show="showActions" ng-swipe-right="showActions = false">
553 <button ng-click="reply()">Reply</button>
554 <button ng-click="delete()">Delete</button>
557 <file name="script.js">
558 angular.module('ngSwipeRightExample', ['ngTouch']);
563 function makeSwipeDirective(directiveName, direction, eventName) {
564 ngTouch.directive(directiveName, ['$parse', '$swipe', function($parse, $swipe) {
565 // The maximum vertical delta for a swipe should be less than 75px.
566 var MAX_VERTICAL_DISTANCE = 75;
567 // Vertical distance should not be more than a fraction of the horizontal distance.
568 var MAX_VERTICAL_RATIO = 0.3;
569 // At least a 30px lateral motion is necessary for a swipe.
570 var MIN_HORIZONTAL_DISTANCE = 30;
572 return function(scope, element, attr) {
573 var swipeHandler = $parse(attr[directiveName]);
575 var startCoords, valid;
577 function validSwipe(coords) {
578 // Check that it's within the coordinates.
579 // Absolute vertical distance must be within tolerances.
580 // Horizontal distance, we take the current X - the starting X.
581 // This is negative for leftward swipes and positive for rightward swipes.
582 // After multiplying by the direction (-1 for left, +1 for right), legal swipes
583 // (ie. same direction as the directive wants) will have a positive delta and
584 // illegal ones a negative delta.
585 // Therefore this delta must be positive, and larger than the minimum.
586 if (!startCoords) return false;
587 var deltaY = Math.abs(coords.y - startCoords.y);
588 var deltaX = (coords.x - startCoords.x) * direction;
589 return valid && // Short circuit for already-invalidated swipes.
590 deltaY < MAX_VERTICAL_DISTANCE &&
592 deltaX > MIN_HORIZONTAL_DISTANCE &&
593 deltaY / deltaX < MAX_VERTICAL_RATIO;
596 var pointerTypes = ['touch'];
597 if (!angular.isDefined(attr['ngSwipeDisableMouse'])) {
598 pointerTypes.push('mouse');
600 $swipe.bind(element, {
601 'start': function(coords, event) {
602 startCoords = coords;
605 'cancel': function(event) {
608 'end': function(coords, event) {
609 if (validSwipe(coords)) {
610 scope.$apply(function() {
611 element.triggerHandler(eventName);
612 swipeHandler(scope, {$event: event});
621 // Left is negative X-coordinate, right is positive.
622 makeSwipeDirective('ngSwipeLeft', -1, 'swipeleft');
623 makeSwipeDirective('ngSwipeRight', 1, 'swiperight');
627 })(window, window.angular);