How to add a confirmation dialog box in AngularJS

Setting up a confirmation box can be quite tricky, here’s how to quickly get a confirmation box setup in AngularJS.

Pre-requisite

  • AngularJS is already loaded and running
  • You are using real jQuery instead of jqLite (I’ll explain below)

Prepare your HTML

First, start off with a blank HTML page.

Create a link that you would like to run a function() on when clicked and
confirmed.

It should look something like this:

<a href="#" ng-click="shoutOut()">Shout!</a>

Good?

Lets add a couple of custom attributes that describes what we want to do with
it.

<a href="#" ng-click="shoutOut()" confirmation-needed="Do you really want to
shout?">Shout!</a>

We’ve added confirmation-needed to define a custom message to be displayed
when we want the user to confirm the results.

Function

With your HTML already looking like how it should look like, lets create the
function

# assuming your code lives in a Angular Controller
app.controller('wooCtrl', function($scope){
  $scope.shout = function() {
    alert('YO MR WHITE!');
  };

});

Excellent.

Directive

Now, lets tell Angular how to handle the custom attribute ‘confirmation-needed’
by writing a custom directive. If you are a little lost at this stage, maybe
this introduction to directives video could help.

Finish this and come back here to continue with the tutorial.

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

Now, if you’re not using jQuery in your app, you’ll probably find yourself
wondering why after following all these steps, you’re running into issues
with the cancellation button still calling the function despite telling it otherwise.

Zach Snow in the comments explains that
there’s an issue with jqlite not able to override the event handler.
So if you’re running on the default jqlite, you might need to run your own
directive to override ngClick or use an old version of
e.originalEvent.stopImmediatePropagation() which might not be compatiable anymore with
most older browsers.

With that, you have your very own confirmable click!