7

在实际触发 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,因为最新的角度有这个新的 ngtouch 指令)。但没有任何效果。

4

1 回答 1

14

啊,我自己解决了

最近 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();
                  }
                });
              }
        }
    }
  }
]);
于 2013-10-15T16:40:28.220 回答