tscizzle
tscizzle

Reputation: 12241

angular - handle ng click, except when that click becomes a drag

The desired behavior is that a user can click on this object (so it has an ng-click) but if the click turns into a drag before mouseup, then the ng-click handler is not fired.

Perhaps a way to detect, given the $event object which I pass to the handler, whether or not the click was a drag, and have a conditional which checks that in the handler?

(motivation is that the clickable object has text, and I want that text to be able to be highlighted and copied without triggering the click)

using angular version 1.5.6

Upvotes: 3

Views: 1447

Answers (2)

Tiago
Tiago

Reputation: 1991

This is how I managed this - in my controller I have this:

        $scope.dragging = false;
        $scope.mouseIsDown = false;
        $scope.mouseDown = function(event){
            //console.log("mouse down");
            $scope.mouseIsDown = true;
            $scope.dragging = false;
        };
        $scope.mouseUp = function(event){
            //console.log("mouse up");
            $scope.mouseIsDown = false;

            if($scope.dragging){
                //console.log("Must have dragged");
                return false;
            }else{
                //handle single click here, since drag didn't happen
            }
        };
        $scope.mouseMove = function(event){
            //console.log("mouse moved");
            $scope.dragging = true;
        };

In my HTML element I have these handles set, although I'm certain this is what Roman meant:

        ng-mousedown="mouseDown(event)"
        ng-mouseup  ="mouseUp(event)"
        ng-mousemove="mouseMove(event)"

Upvotes: 0

Roman Koliada
Roman Koliada

Reputation: 5082

I think you can set both ng-mousedown and ng-mouseup handlers. When ng-mousedown fires you can save coordinates and then calculate the difference with new coordinates inside ng-mouseup event. If the difference is small - it's a click and you can run you ng-click function.

Upvotes: 1

Related Questions