【问题标题】:Prevent ng-click from firing for confirmation dialog (stopped working in Angular 1.2 RC3)防止 ng-click 触发确认对话框(在 Angular 1.2 RC3 中停止工作)
【发布时间】:2013-10-15 16:27:01
【问题描述】:

在实际触发 ng-click 功能之前,我正在使用此脚本进行确认对话框

Directives.directive('ngConfirmClick', [
  function(){
    return {
      priority: 100,
      restrict: 'A',
      link: function(scope, element, attrs){
        element.bind('click', function(e){
          var message = attrs.ngConfirmClick;
          if(message && !confirm(message)){
            e.stopImmediatePropagation();
            e.preventDefault();
          }
        });
      }
    }
  }
]);

如上所示 http://zachsnow.com/#!/blog/2013/confirming-ng-click/

通过以下方式使用:

<button ng-confirm-click="Are you sure?" ng-click="remove()">Remove</button>

在 SO 上还有其他类似的脚本,但是自从我更新到 Angular 1.2 RC3 后它们就停止工作了。 ng-click 函数总是在实际链接函数进入之前触发。

我还尝试增加优先级并监听其他事件(touchstart,因为最新的 Angular 有这个新的 ngtouch 指令)。但没有任何效果。

【问题讨论】:

    标签: javascript angularjs onclick confirm directive


    【解决方案1】:

    啊,我自己解决了

    最近 Angular 团队的一次提交更改了前/后链接优先级: https://github.com/angular/angular.js/commit/31f190d4d53921d32253ba80d9ebe57d6c1de82b

    这现在包含在 Angular 1.2 RC3 中!

    因此,帖子链接功能现在具有相反的优先级。

    所以有两种方法可以解决这个问题。 现在使用否定优先级

    Directives.directive('ngConfirmClick', [
      function(){
        return {
          priority: -100,  //<---------
          restrict: 'A',
          link: function(scope, element, attrs){
            element.bind('click', function(e){
              var message = attrs.ngConfirmClick;
              if(message && !confirm(message)){
                e.stopImmediatePropagation();
                e.preventDefault();
              }
            });
          }
        }
      }
    ]);
    

    将函数转换为预链接函数

    Directives.directive('ngConfirmClick', [
      function(){
        return {
          priority: 100,
          restrict: 'A',
          link: {
              pre: function(scope, element, attrs){ //<---------
                    element.bind('click touchstart', function(e){
                      var message = attrs.ngConfirmClick;
                      if(message && !window.confirm(message)){
                        e.stopImmediatePropagation();
                        e.preventDefault();
                      }
                    });
                  }
            }
        }
      }
    ]);
    

    【讨论】:

    • 我使用后一种方法并将其转换为预链接功能,对我来说似乎比负优先级更自然
    • 这些都不适用于 Angular 1.2.15。您会看到确认对话框,但它不会停止事件传播。知道为什么吗?
    • 对于迟到的答案感到抱歉,但也许它可以帮助其他人。我们使用 Angular 1.2.16,在这里它完全按照上述预期工作。
    • 是的,它适用于 1.2.21,它很干净,谢谢!
    • 谢谢!救命恩人!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 2013-12-01
    • 2011-03-25
    • 2017-06-18
    相关资源
    最近更新 更多