本文介绍了使用 ng-click 自动传递 $event?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如果我像这样传入 $event 对象,我可以从 ng-click 访问点击事件:

I know that I can get access to the click event from ng-click if I pass in the $event object like so:

<button ng-click="myFunction($event)">Give me the $event</button>

<script>
  function myFunction (event) {
    typeof event !== "undefined" // true
  }
</script>

每次都必须显式传递 $event 有点烦人.是否可以设置 ng-click 默认以某种方式将其传递给函数?

It's a little bit annoying having to pass $event explicitly every time. Is it possible to set ng-click to somehow pass it to the function by default?

推荐答案

看一看 ng-click 指令来源:

...
compile: function($element, attr) {
  var fn = $parse(attr[directiveName]);
  return function(scope, element, attr) {
    element.on(lowercase(name), function(event) {
      scope.$apply(function() {
        fn(scope, {$event:event});
      });
    });
  };
}

它展示了event 对象正在传递ng-click 表达式,使用 $event 作为参数名称.这是由 $parse 服务完成的,它不允许参数渗入目标范围,这意味着答案是否定的,您无法访问$event 对象的任何其他方式,但通过回调参数.

It shows how the event object is being passed on to the ng-click expression, using $event as a name of the parameter. This is done by the $parse service, which doesn't allow for the parameters to bleed into the target scope, which means the answer is no, you can't access the $event object any other way but through the callback parameter.

这篇关于使用 ng-click 自动传递 $event?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:11