为什么AngularJS中的$ event.preventDefault()不会阻止上下文菜单出现? [英] Why does $event.preventDefault() in AngularJS not prevent context menu from appearing?

查看:211
本文介绍了为什么AngularJS中的$ event.preventDefault()不会阻止上下文菜单出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如标题所示,我不知道为什么 $ event.preventDefault()不会阻止右键单击显示上下文菜单。

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

我在plunker中写了这个简单的例子来演示问题。

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:

Javascript:

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

提前感谢

推荐答案

为了防止上下文菜单,您需要捕获(并阻止) contextmenu 事件。

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

不幸的是,Angular没有这个事件的指令,所以你必须自己创建一个。

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

从Angular的源代码(版本1.2.16)复制:

"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>






另请参阅 短演示

最新测试版本的Chrome,Firefox和Safari,并发现工作。

这篇关于为什么AngularJS中的$ event.preventDefault()不会阻止上下文菜单出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆