BetaRide
BetaRide

Reputation: 16844

preventDefault is not stopping default mouse handlng

I have this simple angular example where I want to capture a mouse right click for a custom action. The default context menu must not show up. I read the questions here at SO. Unfortunately I cannot stop it from opening the browser built in context menu. I'm sure I'm missing something simple here. (see plunker http://plnkr.co/edit/YieQh23xNUFmPrjZscGB)

index.html

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8" />
    <title>My Plunk</title>
    <script data-require="[email protected]" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-app="plunker" ng-controller="myController">
    <p ng-mousedown="mouseClicked($event)">Click me!</p>
  </body>

</html>

script.js

var app = angular.module('plunker', []);

app.controller('myController', ['$scope', '$log', function($scope, $log) {
  $scope.mouseClicked = function(event) {
    if (event.button===2) {
      $log.debug('right mouse click detected')
      // don't do anything else
      event.preventDefault();
      event.stopPropagation();
    }
  };
}]);

Upvotes: 1

Views: 142

Answers (1)

MMhunter
MMhunter

Reputation: 1441

If you are going to disable the context menu, you need to listen to the contextmenu event in order to stop it.

To achieve this in angular, maybe you need to add a custom directive:

app.directive('noContextMenu', [function() {
  return function(scope, ele, attr){
    ele.on('contextmenu', function(e) {
      e.preventDefault();
    });
  }
}]);
<p no-context-menu >Click me!</p>

Upvotes: 2

Related Questions