使用 ng-click 自动传递 $event? [英] Automatically pass $event with ng-click?

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

问题描述

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

<button ng-click="myFunction($event)">给我 $event</button><脚本>函数 myFunction(事件){typeof event !== "undefined"//true}

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

解决方案

看一看 ng-click 指令来源:

<预><代码>...编译:函数($元素,属性){var fn = $parse(attr[directiveName]);返回函数(范围,元素,属性){element.on(小写(名称),函数(事件){范围.$应用(函数(){fn(scope, {$event:event});});});};}

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

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>

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?

解决方案

Take a peek at the ng-click directive source:

...
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});
      });
    });
  };
}

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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