在 angularJS 中拦截 ng-click [英] Intercepting ng-click in angularJS

查看:39
本文介绍了在 angularJS 中拦截 ng-click的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为 ng-click 编写拦截器?我有一个按钮或链接,可导致删除后端中的对象.我想通过向按钮/链接添加一个属性来获得一个确认对话框(模态).例如:

is it possible to write an interceptor for ng-click? I have a button or a link that leads to a deletion of an object in the backend. I'd like to have a confirmation dialog (modal) by just adding an attribute to the button/link. E.g.:

<a href="#" ng-click="deleteIt(id)" confirmation-needed>Delete</a>

这可以用 AngularJS 实现吗?有没有更好的方法来解决这个问题?

Is this possible with AngularJS? Is there a better approach do solve this issue?

EDIT deleteIt 方法驻留在不同的控制器中.

EDIT The deleteIt method resides in different controllers.

谢谢

推荐答案

我在:

http://plnkr.co/edit/GJwK7ldGa9LY90bMuOfl?p=preview

我通过创建一个指令来实现它:

I achieve it by creating a directive:

  1. 具有比 ngClick 更高的 priority,因此它在 ngClick 之前被调用,
  2. 制作终端,使其不调用ngClick.
  3. 监听点击事件,然后在消息正常时评估 ngClick 值.
  1. with a higher priority than ngClick, so that it gets called before ngClick,
  2. making that terminal so that it doesn't call ngClick.
  3. listening to click events, and then evaluating the ngClick value if the message is ok.

作为奖励,您可以传入您自己的消息,例如:

As a bonus, you can pass in your own message, such as:

<a href="#" ng-click="deleteIt(id)" 
    confirmation-needed="Really Delete?"
        >Delete with custom message</a>

代码如下:

app.directive('confirmationNeeded', function () {
  return {
    priority: 1,
    terminal: true,
    link: function (scope, element, attr) {
      var msg = attr.confirmationNeeded || "Are you sure?";
      var clickAction = attr.ngClick;
      element.bind('click',function () {
        if ( window.confirm(msg) ) {
          scope.$eval(clickAction)
        }
      });
    }
  };
});

希望有所帮助.

这篇关于在 angularJS 中拦截 ng-click的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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