Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does $event.preventDefault() in AngularJS not prevent context menu from appearing?

Like the title says, I'm not sure why $event.preventDefault() is not preventing the context menu from appearing on right click.

I've written this simple example in plunker to demonstrate the problem.

Html:

<body ng-controller="MainCtrl">
    <div id="me" ng-mousedown="stopContext($event)">CLICK ME {{num}}</div>
</body>

Javascript:

  $scope.stopContext = function(ev) {
    $scope.num += 1;
    ev.preventDefault();
  };

Thanks in advance.

like image 287
Ben Avatar asked May 11 '14 07:05

Ben


People also ask

What does event preventDefault () do?

Event.preventDefault() The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

What is the use of preventDefault in angular?

preventDefault() method prevents the default behavior of an element. If we use form element it prevents form submitting. If we use a href element it prevents navigating.

How do I disable browser context menu?

The context menu usually has a list of actions like "View Page Source" and "Back". We can prevent this menu from appearing on right-click by latching onto the contextmenu event and using event. preventDefault() . If we add this event listener to the window object then we can prevent right-clicking on the whole page.


1 Answers

In order to prevent the context-menu you need to capture (and prevent) the contextmenu event.

Unfortunately, Angular does not have a directive for this event, so you'll have to create one yourself.

"Copying" from the source code of Angular (version 1.2.16):

app.directive('myContextmenu', function ($parse) {
  return {
    compile: function (tElem, tAttrs) {
      var fn = $parse(tAttrs.myContextmenu);

      return function (scope, elem) {
        elem.on('contextmenu', onContextmenu);

        function onContextmenu(evt) {
          scope.$apply(function () {
            fn(scope, {$event: evt});
          });
        });
      };
    }
  };
});

Then, you can use it like this:

<div id="me" my-contextmenu="stopContext($event)">CLICK ME {{num}}</div>

See, also, this short demo.
Tested on latest version of Chrome, Firefox and Safari and found working.

like image 146
gkalpak Avatar answered Oct 09 '22 23:10

gkalpak