Why doesn't $ event.preventDefault () in AngularJS prevent the context menu from appearing?

As in the title, I'm not sure why $event.preventDefault() does not prevent the context menu from appearing on the right.

I wrote 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.

+6
source share
1 answer

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 have to create it yourself.

"Copying" from Angular source code (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 as follows:

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

See also this short demo .
Tested in the latest version of Chrome, Firefox and Safari and found a job.

+12
source

All Articles