Skip to content

Instantly share code, notes, and snippets.

@BobNisco
Last active February 27, 2023 15:43
Show Gist options
  • Save BobNisco/9885852 to your computer and use it in GitHub Desktop.
Save BobNisco/9885852 to your computer and use it in GitHub Desktop.
onLongPress AngularJS Directive - Great for mobile!
// Somewhere in your controllers for this given example
// Example functions
$scope.itemOnLongPress = function(id) {
console.log('Long press');
}
$scope.itemOnTouchEnd = function(id) {
console.log('Touch end');
}
// Add this directive where you keep your directives
.directive('onLongPress', function($timeout) {
return {
restrict: 'A',
link: function($scope, $elm, $attrs) {
$elm.bind('touchstart', function(evt) {
// Locally scoped variable that will keep track of the long press
$scope.longPress = true;
// We'll set a timeout for 600 ms for a long press
$timeout(function() {
if ($scope.longPress) {
// If the touchend event hasn't fired,
// apply the function given in on the element's on-long-press attribute
$scope.$apply(function() {
$scope.$eval($attrs.onLongPress)
});
}
}, 600);
});
$elm.bind('touchend', function(evt) {
// Prevent the onLongPress event from firing
$scope.longPress = false;
// If there is an on-touch-end function attached to this element, apply it
if ($attrs.onTouchEnd) {
$scope.$apply(function() {
$scope.$eval($attrs.onTouchEnd)
});
}
});
}
};
})
<ion-item ng-repeat="item in list" on-long-press="itemOnLongPress(item.id)" on-touch-end="itemOnTouchEnd(item.id)">
{{ item }}
</ion-item>
@marcramser
Copy link

Thanks a lot! Save me much time.

@raviji
Copy link

raviji commented Sep 17, 2016

For me not working on ipad guys, please help me out

@Vespira
Copy link

Vespira commented Sep 19, 2016

Thanks I took this code and adapted it, it works well. I'm just not sure it's a good thing to manually "$eval" methods. I've heard that normally you should always let angular eval automatically the things at each cycle.

@3Nex
Copy link

3Nex commented Sep 26, 2016

I've found that the long press event fires even if you just grab on that element to scroll down the page. So I've added the following touchmove event to cancel the long press from firing, and prevent that behavior:

$elm.bind("touchmove", function(evt) {
    $scope.longPress = false;
});

or for @mbaer3000's solution:

elem.bind("touchmove", function(evt) {
    $timeout.cancel(timeoutHandler);
});

@bharathidhasanS
Copy link

touchmove event not working as expected. Any help

@bhuvan-socialcurry
Copy link

i need to select multiple elements on long press can somebody help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment