Skip to content

Instantly share code, notes, and snippets.

@OrenShalev
Forked from BobNisco/controller.js
Last active January 6, 2016 11:18
Show Gist options
  • Save OrenShalev/8051567f9485ac78dbba to your computer and use it in GitHub Desktop.
Save OrenShalev/8051567f9485ac78dbba 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.itemOnMouseUp = function(id) {
console.log('Mouse up');
}
// Add this directive where you keep your directives
.directive('onLongPress', function($timeout) {
return {
restrict: 'A',
link: function($scope, $elm, $attrs) {
$elm.bind('mousedown', 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 mouseup 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('mouseup', 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.onmouseup) {
$scope.$apply(function() {
$scope.$eval($attrs.onmouseup)
});
}
});
}
};
})
<ion-item ng-repeat="item in list" on-long-press="itemOnLongPress(item.id)" on-touch-end="itemOnMouseUp(item.id)">
{{ item }}
</ion-item>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment