Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent ng-click from firing for confirmation dialog (stopped working in Angular 1.2 RC3)

I'm using this script to have a confirmation dialog before actually firing the ng-click function

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();
          }
        });
      }
    }
  }
]);

as seen on http://zachsnow.com/#!/blog/2013/confirming-ng-click/

it's used via:

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

There are other similar scripts here on SO, but since i updated to Angular 1.2 RC3 they stopped working. The ng-click function is always fired BEFORE the actual link function is stepped into.

I also tried to increase priority and to listen to other events(touchstart, because the newest angular has this new ngtouch directives). But nothing works.

like image 793
Eike Thies Avatar asked Oct 15 '13 16:10

Eike Thies


1 Answers

Ah i got it solved myself!

Recently there was a commit by the angular team that changed the pre/post linking priority: https://github.com/angular/angular.js/commit/31f190d4d53921d32253ba80d9ebe57d6c1de82b

This is now included in Angular 1.2 RC3!

Therefore the post linking function has now a reversed priority.

So there are two ways to solve this. Either use a negative priority now

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();
          }
        });
      }
    }
  }
]);

OR convert the function to a pre linking function

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();
                  }
                });
              }
        }
    }
  }
]);
like image 160
Eike Thies Avatar answered Nov 10 '22 00:11

Eike Thies