2 * @license AngularJS v1.5.0
3 * (c) 2010-2016 Google, Inc. http://angularjs.org
6 (function(window, angular, undefined) {'use strict';
8 /* global ngTouchClickDirectiveFactory: false,
18 * The `ngTouch` module provides touch events and other helpers for touch-enabled devices.
19 * The implementation is based on jQuery Mobile touch event handling
20 * ([jquerymobile.com](http://jquerymobile.com/)).
23 * See {@link ngTouch.$swipe `$swipe`} for usage.
25 * <div doc-module-components="ngTouch"></div>
29 // define ngTouch module
31 var ngTouch = angular.module('ngTouch', []);
33 ngTouch.provider('$touch', $TouchProvider);
35 function nodeName_(element) {
36 return angular.lowercase(element.nodeName || (element[0] && element[0].nodeName));
41 * @name $touchProvider
44 * The `$touchProvider` allows enabling / disabling {@link ngTouch.ngClick ngTouch's ngClick directive}.
46 $TouchProvider.$inject = ['$provide', '$compileProvider'];
47 function $TouchProvider($provide, $compileProvider) {
51 * @name $touchProvider#ngClickOverrideEnabled
53 * @param {boolean=} enabled update the ngClickOverrideEnabled state if provided, otherwise just return the
54 * current ngClickOverrideEnabled state
55 * @returns {*} current value if used as getter or itself (chaining) if used as setter
60 * Call this method to enable/disable {@link ngTouch.ngClick ngTouch's ngClick directive}. If enabled,
61 * the default ngClick directive will be replaced by a version that eliminates the 300ms delay for
62 * click events on browser for touch-devices.
64 * The default is `false`.
67 var ngClickOverrideEnabled = false;
68 var ngClickDirectiveAdded = false;
69 this.ngClickOverrideEnabled = function(enabled) {
70 if (angular.isDefined(enabled)) {
72 if (enabled && !ngClickDirectiveAdded) {
73 ngClickDirectiveAdded = true;
75 // Use this to identify the correct directive in the delegate
76 ngTouchClickDirectiveFactory.$$moduleName = 'ngTouch';
77 $compileProvider.directive('ngClick', ngTouchClickDirectiveFactory);
79 $provide.decorator('ngClickDirective', ['$delegate', function($delegate) {
80 if (ngClickOverrideEnabled) {
81 // drop the default ngClick directive
84 // drop the ngTouch ngClick directive if the override has been re-disabled (because
85 // we cannot de-register added directives)
86 var i = $delegate.length - 1;
88 if ($delegate[i].$$moduleName === 'ngTouch') {
89 $delegate.splice(i, 1);
100 ngClickOverrideEnabled = enabled;
104 return ngClickOverrideEnabled;
113 * Provides the {@link ngTouch.$touch#ngClickOverrideEnabled `ngClickOverrideEnabled`} method.
116 this.$get = function() {
120 * @name $touch#ngClickOverrideEnabled
122 * @returns {*} current value of `ngClickOverrideEnabled` set in the {@link ngTouch.$touchProvider $touchProvider},
123 * i.e. if {@link ngTouch.ngClick ngTouch's ngClick} directive is enabled.
127 ngClickOverrideEnabled: function() {
128 return ngClickOverrideEnabled;
135 /* global ngTouch: false */
142 * The `$swipe` service is a service that abstracts the messier details of hold-and-drag swipe
143 * behavior, to make implementing swipe-related directives more convenient.
145 * Requires the {@link ngTouch `ngTouch`} module to be installed.
147 * `$swipe` is used by the `ngSwipeLeft` and `ngSwipeRight` directives in `ngTouch`.
150 * The `$swipe` service is an object with a single method: `bind`. `bind` takes an element
151 * which is to be watched for swipes, and an object with four handler functions. See the
152 * documentation for `bind` below.
155 ngTouch.factory('$swipe', [function() {
156 // The total distance in any direction before we make the call on swipe vs. scroll.
157 var MOVE_BUFFER_RADIUS = 10;
159 var POINTER_EVENTS = {
169 cancel: 'touchcancel'
173 function getCoordinates(event) {
174 var originalEvent = event.originalEvent || event;
175 var touches = originalEvent.touches && originalEvent.touches.length ? originalEvent.touches : [originalEvent];
176 var e = (originalEvent.changedTouches && originalEvent.changedTouches[0]) || touches[0];
184 function getEvents(pointerTypes, eventType) {
186 angular.forEach(pointerTypes, function(pointerType) {
187 var eventName = POINTER_EVENTS[pointerType][eventType];
192 return res.join(' ');
201 * The main method of `$swipe`. It takes an element to be watched for swipe motions, and an
202 * object containing event handlers.
203 * The pointer types that should be used can be specified via the optional
204 * third argument, which is an array of strings `'mouse'` and `'touch'`. By default,
205 * `$swipe` will listen for `mouse` and `touch` events.
207 * The four events are `start`, `move`, `end`, and `cancel`. `start`, `move`, and `end`
208 * receive as a parameter a coordinates object of the form `{ x: 150, y: 310 }` and the raw
209 * `event`. `cancel` receives the raw `event` as its single parameter.
211 * `start` is called on either `mousedown` or `touchstart`. After this event, `$swipe` is
212 * watching for `touchmove` or `mousemove` events. These events are ignored until the total
213 * distance moved in either dimension exceeds a small threshold.
215 * Once this threshold is exceeded, either the horizontal or vertical delta is greater.
216 * - If the horizontal distance is greater, this is a swipe and `move` and `end` events follow.
217 * - If the vertical distance is greater, this is a scroll, and we let the browser take over.
218 * A `cancel` event is sent.
220 * `move` is called on `mousemove` and `touchmove` after the above logic has determined that
221 * a swipe is in progress.
223 * `end` is called when a swipe is successfully completed with a `touchend` or `mouseup`.
225 * `cancel` is called either on a `touchcancel` from the browser, or when we begin scrolling
226 * as described above.
229 bind: function(element, eventHandlers, pointerTypes) {
230 // Absolute total movement, used to control swipe vs. scroll.
232 // Coordinates of the start position.
234 // Last event's position.
236 // Whether a swipe is active.
239 pointerTypes = pointerTypes || ['mouse', 'touch'];
240 element.on(getEvents(pointerTypes, 'start'), function(event) {
241 startCoords = getCoordinates(event);
245 lastPos = startCoords;
246 eventHandlers['start'] && eventHandlers['start'](startCoords, event);
248 var events = getEvents(pointerTypes, 'cancel');
250 element.on(events, function(event) {
252 eventHandlers['cancel'] && eventHandlers['cancel'](event);
256 element.on(getEvents(pointerTypes, 'move'), function(event) {
259 // Android will send a touchcancel if it thinks we're starting to scroll.
260 // So when the total distance (+ or - or both) exceeds 10px in either direction,
262 // - On totalX > totalY, we send preventDefault() and treat this as a swipe.
263 // - On totalY > totalX, we let the browser handle it as a scroll.
265 if (!startCoords) return;
266 var coords = getCoordinates(event);
268 totalX += Math.abs(coords.x - lastPos.x);
269 totalY += Math.abs(coords.y - lastPos.y);
273 if (totalX < MOVE_BUFFER_RADIUS && totalY < MOVE_BUFFER_RADIUS) {
277 // One of totalX or totalY has exceeded the buffer, so decide on swipe vs. scroll.
278 if (totalY > totalX) {
279 // Allow native scrolling to take over.
281 eventHandlers['cancel'] && eventHandlers['cancel'](event);
284 // Prevent the browser from scrolling.
285 event.preventDefault();
286 eventHandlers['move'] && eventHandlers['move'](coords, event);
290 element.on(getEvents(pointerTypes, 'end'), function(event) {
293 eventHandlers['end'] && eventHandlers['end'](getCoordinates(event), event);
299 /* global ngTouch: false,
309 * <div class="alert alert-danger">
310 * **DEPRECATION NOTICE**: Beginning with Angular 1.5, this directive is deprecated and by default **disabled**.
311 * The directive will receive no further support and might be removed from future releases.
312 * If you need the directive, you can enable it with the {@link ngTouch.$touchProvider $touchProvider#ngClickOverrideEnabled}
313 * function. We also recommend that you migrate to [FastClick](https://github.com/ftlabs/fastclick).
314 * To learn more about the 300ms delay, this [Telerik article](http://developer.telerik.com/featured/300-ms-click-delay-ios-8/)
315 * gives a good overview.
317 * A more powerful replacement for the default ngClick designed to be used on touchscreen
318 * devices. Most mobile browsers wait about 300ms after a tap-and-release before sending
319 * the click event. This version handles them immediately, and then prevents the
320 * following click event from propagating.
322 * Requires the {@link ngTouch `ngTouch`} module to be installed.
324 * This directive can fall back to using an ordinary click event, and so works on desktop
325 * browsers as well as mobile.
327 * This directive also sets the CSS class `ng-click-active` while the element is being held
328 * down (by a mouse click or touch) so you can restyle the depressed element if you wish.
331 * @param {expression} ngClick {@link guide/expression Expression} to evaluate
332 * upon tap. (Event object is available as `$event`)
335 <example module="ngClickExample" deps="angular-touch.js">
336 <file name="index.html">
337 <button ng-click="count = count + 1" ng-init="count=0">
342 <file name="script.js">
343 angular.module('ngClickExample', ['ngTouch']);
348 var ngTouchClickDirectiveFactory = ['$parse', '$timeout', '$rootElement',
349 function($parse, $timeout, $rootElement) {
350 var TAP_DURATION = 750; // Shorter than 750ms is a tap, longer is a taphold or drag.
351 var MOVE_TOLERANCE = 12; // 12px seems to work in most mobile browsers.
352 var PREVENT_DURATION = 2500; // 2.5 seconds maximum from preventGhostClick call to click
353 var CLICKBUSTER_THRESHOLD = 25; // 25 pixels in any dimension is the limit for busting clicks.
355 var ACTIVE_CLASS_NAME = 'ng-click-active';
356 var lastPreventedTime;
357 var touchCoordinates;
358 var lastLabelClickCoordinates;
361 // TAP EVENTS AND GHOST CLICKS
364 // Mobile browsers detect a tap, then wait a moment (usually ~300ms) to see if you're
365 // double-tapping, and then fire a click event.
367 // This delay sucks and makes mobile apps feel unresponsive.
368 // So we detect touchstart, touchcancel and touchend ourselves and determine when
369 // the user has tapped on something.
371 // What happens when the browser then generates a click event?
372 // The browser, of course, also detects the tap and fires a click after a delay. This results in
373 // tapping/clicking twice. We do "clickbusting" to prevent it.
376 // We attach global touchstart and click handlers, that run during the capture (early) phase.
377 // So the sequence for a tap is:
378 // - global touchstart: Sets an "allowable region" at the point touched.
379 // - element's touchstart: Starts a touch
380 // (- touchcancel ends the touch, no click follows)
381 // - element's touchend: Determines if the tap is valid (didn't move too far away, didn't hold
382 // too long) and fires the user's tap handler. The touchend also calls preventGhostClick().
383 // - preventGhostClick() removes the allowable region the global touchstart created.
384 // - The browser generates a click event.
385 // - The global click handler catches the click, and checks whether it was in an allowable region.
386 // - If preventGhostClick was called, the region will have been removed, the click is busted.
387 // - If the region is still there, the click proceeds normally. Therefore clicks on links and
388 // other elements without ngTap on them work normally.
390 // This is an ugly, terrible hack!
391 // Yeah, tell me about it. The alternatives are using the slow click events, or making our users
392 // deal with the ghost clicks, so I consider this the least of evils. Fortunately Angular
393 // encapsulates this ugly logic away from the user.
395 // Why not just put click handlers on the element?
396 // We do that too, just to be sure. If the tap event caused the DOM to change,
397 // it is possible another element is now in that position. To take account for these possibly
398 // distinct elements, the handlers are global and care only about coordinates.
400 // Checks if the coordinates are close enough to be within the region.
401 function hit(x1, y1, x2, y2) {
402 return Math.abs(x1 - x2) < CLICKBUSTER_THRESHOLD && Math.abs(y1 - y2) < CLICKBUSTER_THRESHOLD;
405 // Checks a list of allowable regions against a click location.
406 // Returns true if the click should be allowed.
407 // Splices out the allowable region from the list after it has been used.
408 function checkAllowableRegions(touchCoordinates, x, y) {
409 for (var i = 0; i < touchCoordinates.length; i += 2) {
410 if (hit(touchCoordinates[i], touchCoordinates[i + 1], x, y)) {
411 touchCoordinates.splice(i, i + 2);
412 return true; // allowable region
415 return false; // No allowable region; bust it.
418 // Global click handler that prevents the click if it's in a bustable zone and preventGhostClick
419 // was called recently.
420 function onClick(event) {
421 if (Date.now() - lastPreventedTime > PREVENT_DURATION) {
425 var touches = event.touches && event.touches.length ? event.touches : [event];
426 var x = touches[0].clientX;
427 var y = touches[0].clientY;
428 // Work around desktop Webkit quirk where clicking a label will fire two clicks (on the label
429 // and on the input element). Depending on the exact browser, this second click we don't want
430 // to bust has either (0,0), negative coordinates, or coordinates equal to triggering label
432 if (x < 1 && y < 1) {
435 if (lastLabelClickCoordinates &&
436 lastLabelClickCoordinates[0] === x && lastLabelClickCoordinates[1] === y) {
437 return; // input click triggered by label click
439 // reset label click coordinates on first subsequent click
440 if (lastLabelClickCoordinates) {
441 lastLabelClickCoordinates = null;
443 // remember label click coordinates to prevent click busting of trigger click event on input
444 if (nodeName_(event.target) === 'label') {
445 lastLabelClickCoordinates = [x, y];
448 // Look for an allowable region containing this click.
449 // If we find one, that means it was created by touchstart and not removed by
450 // preventGhostClick, so we don't bust it.
451 if (checkAllowableRegions(touchCoordinates, x, y)) {
455 // If we didn't find an allowable region, bust the click.
456 event.stopPropagation();
457 event.preventDefault();
459 // Blur focused form elements
460 event.target && event.target.blur && event.target.blur();
464 // Global touchstart handler that creates an allowable region for a click event.
465 // This allowable region can be removed by preventGhostClick if we want to bust it.
466 function onTouchStart(event) {
467 var touches = event.touches && event.touches.length ? event.touches : [event];
468 var x = touches[0].clientX;
469 var y = touches[0].clientY;
470 touchCoordinates.push(x, y);
472 $timeout(function() {
473 // Remove the allowable region.
474 for (var i = 0; i < touchCoordinates.length; i += 2) {
475 if (touchCoordinates[i] == x && touchCoordinates[i + 1] == y) {
476 touchCoordinates.splice(i, i + 2);
480 }, PREVENT_DURATION, false);
483 // On the first call, attaches some event handlers. Then whenever it gets called, it creates a
484 // zone around the touchstart where clicks will get busted.
485 function preventGhostClick(x, y) {
486 if (!touchCoordinates) {
487 $rootElement[0].addEventListener('click', onClick, true);
488 $rootElement[0].addEventListener('touchstart', onTouchStart, true);
489 touchCoordinates = [];
492 lastPreventedTime = Date.now();
494 checkAllowableRegions(touchCoordinates, x, y);
497 // Actual linking function.
498 return function(scope, element, attr) {
499 var clickHandler = $parse(attr.ngClick),
501 tapElement, // Used to blur the element after a tap.
502 startTime, // Used to check if the tap was held too long.
506 function resetState() {
508 element.removeClass(ACTIVE_CLASS_NAME);
511 element.on('touchstart', function(event) {
513 tapElement = event.target ? event.target : event.srcElement; // IE uses srcElement.
514 // Hack for Safari, which can target text nodes instead of containers.
515 if (tapElement.nodeType == 3) {
516 tapElement = tapElement.parentNode;
519 element.addClass(ACTIVE_CLASS_NAME);
521 startTime = Date.now();
523 // Use jQuery originalEvent
524 var originalEvent = event.originalEvent || event;
525 var touches = originalEvent.touches && originalEvent.touches.length ? originalEvent.touches : [originalEvent];
527 touchStartX = e.clientX;
528 touchStartY = e.clientY;
531 element.on('touchcancel', function(event) {
535 element.on('touchend', function(event) {
536 var diff = Date.now() - startTime;
538 // Use jQuery originalEvent
539 var originalEvent = event.originalEvent || event;
540 var touches = (originalEvent.changedTouches && originalEvent.changedTouches.length) ?
541 originalEvent.changedTouches :
542 ((originalEvent.touches && originalEvent.touches.length) ? originalEvent.touches : [originalEvent]);
546 var dist = Math.sqrt(Math.pow(x - touchStartX, 2) + Math.pow(y - touchStartY, 2));
548 if (tapping && diff < TAP_DURATION && dist < MOVE_TOLERANCE) {
549 // Call preventGhostClick so the clickbuster will catch the corresponding click.
550 preventGhostClick(x, y);
552 // Blur the focused element (the button, probably) before firing the callback.
553 // This doesn't work perfectly on Android Chrome, but seems to work elsewhere.
554 // I couldn't get anything to work reliably on Android Chrome.
559 if (!angular.isDefined(attr.disabled) || attr.disabled === false) {
560 element.triggerHandler('click', [event]);
567 // Hack for iOS Safari's benefit. It goes searching for onclick handlers and is liable to click
568 // something else nearby.
569 element.onclick = function(event) { };
571 // Actual click handler.
572 // There are three different kinds of clicks, only two of which reach this point.
573 // - On desktop browsers without touch events, their clicks will always come here.
574 // - On mobile browsers, the simulated "fast" click will call this.
575 // - But the browser's follow-up slow click will be "busted" before it reaches this handler.
576 // Therefore it's safe to use this directive on both mobile and desktop.
577 element.on('click', function(event, touchend) {
578 scope.$apply(function() {
579 clickHandler(scope, {$event: (touchend || event)});
583 element.on('mousedown', function(event) {
584 element.addClass(ACTIVE_CLASS_NAME);
587 element.on('mousemove mouseup', function(event) {
588 element.removeClass(ACTIVE_CLASS_NAME);
594 /* global ngTouch: false */
601 * Specify custom behavior when an element is swiped to the left on a touchscreen device.
602 * A leftward swipe is a quick, right-to-left slide of the finger.
603 * Though ngSwipeLeft is designed for touch-based devices, it will work with a mouse click and drag
606 * To disable the mouse click and drag functionality, add `ng-swipe-disable-mouse` to
607 * the `ng-swipe-left` or `ng-swipe-right` DOM Element.
609 * Requires the {@link ngTouch `ngTouch`} module to be installed.
612 * @param {expression} ngSwipeLeft {@link guide/expression Expression} to evaluate
613 * upon left swipe. (Event object is available as `$event`)
616 <example module="ngSwipeLeftExample" deps="angular-touch.js">
617 <file name="index.html">
618 <div ng-show="!showActions" ng-swipe-left="showActions = true">
619 Some list content, like an email in the inbox
621 <div ng-show="showActions" ng-swipe-right="showActions = false">
622 <button ng-click="reply()">Reply</button>
623 <button ng-click="delete()">Delete</button>
626 <file name="script.js">
627 angular.module('ngSwipeLeftExample', ['ngTouch']);
637 * Specify custom behavior when an element is swiped to the right on a touchscreen device.
638 * A rightward swipe is a quick, left-to-right slide of the finger.
639 * Though ngSwipeRight is designed for touch-based devices, it will work with a mouse click and drag
642 * Requires the {@link ngTouch `ngTouch`} module to be installed.
645 * @param {expression} ngSwipeRight {@link guide/expression Expression} to evaluate
646 * upon right swipe. (Event object is available as `$event`)
649 <example module="ngSwipeRightExample" deps="angular-touch.js">
650 <file name="index.html">
651 <div ng-show="!showActions" ng-swipe-left="showActions = true">
652 Some list content, like an email in the inbox
654 <div ng-show="showActions" ng-swipe-right="showActions = false">
655 <button ng-click="reply()">Reply</button>
656 <button ng-click="delete()">Delete</button>
659 <file name="script.js">
660 angular.module('ngSwipeRightExample', ['ngTouch']);
665 function makeSwipeDirective(directiveName, direction, eventName) {
666 ngTouch.directive(directiveName, ['$parse', '$swipe', function($parse, $swipe) {
667 // The maximum vertical delta for a swipe should be less than 75px.
668 var MAX_VERTICAL_DISTANCE = 75;
669 // Vertical distance should not be more than a fraction of the horizontal distance.
670 var MAX_VERTICAL_RATIO = 0.3;
671 // At least a 30px lateral motion is necessary for a swipe.
672 var MIN_HORIZONTAL_DISTANCE = 30;
674 return function(scope, element, attr) {
675 var swipeHandler = $parse(attr[directiveName]);
677 var startCoords, valid;
679 function validSwipe(coords) {
680 // Check that it's within the coordinates.
681 // Absolute vertical distance must be within tolerances.
682 // Horizontal distance, we take the current X - the starting X.
683 // This is negative for leftward swipes and positive for rightward swipes.
684 // After multiplying by the direction (-1 for left, +1 for right), legal swipes
685 // (ie. same direction as the directive wants) will have a positive delta and
686 // illegal ones a negative delta.
687 // Therefore this delta must be positive, and larger than the minimum.
688 if (!startCoords) return false;
689 var deltaY = Math.abs(coords.y - startCoords.y);
690 var deltaX = (coords.x - startCoords.x) * direction;
691 return valid && // Short circuit for already-invalidated swipes.
692 deltaY < MAX_VERTICAL_DISTANCE &&
694 deltaX > MIN_HORIZONTAL_DISTANCE &&
695 deltaY / deltaX < MAX_VERTICAL_RATIO;
698 var pointerTypes = ['touch'];
699 if (!angular.isDefined(attr['ngSwipeDisableMouse'])) {
700 pointerTypes.push('mouse');
702 $swipe.bind(element, {
703 'start': function(coords, event) {
704 startCoords = coords;
707 'cancel': function(event) {
710 'end': function(coords, event) {
711 if (validSwipe(coords)) {
712 scope.$apply(function() {
713 element.triggerHandler(eventName);
714 swipeHandler(scope, {$event: event});
723 // Left is negative X-coordinate, right is positive.
724 makeSwipeDirective('ngSwipeLeft', -1, 'swipeleft');
725 makeSwipeDirective('ngSwipeRight', 1, 'swiperight');
729 })(window, window.angular);