Created
August 5, 2014 02:49
-
-
Save jessehouchins/0b2415b5673cc1c71fff to your computer and use it in GitHub Desktop.
Angular Double Click (that prevents single click)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.directive('doubleClick', function($timeout, _) { | |
var CLICK_DELAY = 300 | |
var $ = angular.element | |
var omitProperties = 'isDefaultPrevented isImmediatePropagationStopped isPropagationStopped'.split(' ') | |
return { | |
restrict: 'A', | |
link: function(scope, element, attrs) { | |
var clickCount = 0 | |
var clickTimeout | |
var clickEvent | |
function doubleClick(e) { | |
e.preventDefault() | |
e.stopImmediatePropagation() | |
$timeout.cancel(clickTimeout) | |
clickCount = 0 | |
scope.$apply(function() { scope.$eval(attrs.doubleClick) }) | |
} | |
function singleClick(originalEvent) { | |
clickCount = 0 | |
if (attrs.ngClick) scope.$apply(function() { scope.$eval(attrs.ngClick) }) | |
if (originalEvent) { | |
clonedEventData = _.omit.apply(_, [originalEvent].concat(omitProperties)) | |
clickEvent = $.Event('click', clonedEventData) | |
element.trigger(clickEvent) | |
} | |
} | |
function delaySingleClick(e) { | |
e.preventDefault() | |
e.stopImmediatePropagation() | |
clickTimeout = $timeout(singleClick.bind(null, e), CLICK_DELAY) | |
} | |
element.bind('click', function(e) { | |
if (e === clickEvent) return | |
if (clickCount++) doubleClick(e) | |
else delaySingleClick(e) | |
}) | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment