Iulia Mihet
Iulia Mihet

Reputation: 700

Angular Material $mdDialog.confirm with more than "OK" and "Cancel" options

I have to build an $mdDialog window in Angular Material so that the user can select from different actions. Based on the selected actions, the app will either generate a new report or load an already existing report, or Cancel the dialog altogether. The problem is that the confirm $mdDialog has only the .ok option and .cancel option built in it, if you look at the documentation on the Angular Material site (I attached a print screen with the demo code snippet from the site).

$mdDialog confirm demo code

So now my question is: how can I add multiple action options to my $mdDialog window. Also, how do I tie functions to those options in the controller? For example, if you select "Generate new report", then a certain service would fire, but if you select "Show me the previous report", another service to fire. Sorry if this is a beginner question, but I feel like I am again not fully grasping the correct AngularJS logic to be applied in this situation.

Upvotes: 4

Views: 6795

Answers (2)

Mike Feltman
Mike Feltman

Reputation: 5176

@Aseem, sorry to copy your code for an answer, but I couldn't do this in a comment.

One thing is missing from Aseem's answer. If you add a parameter to the then function it will receive the caption of the button the user clicked. So if we modify this just a bit to:

var confirm = $mdDialog.confirm({
  controller: DialogController,
  templateUrl: 'dialog1.tmpl.html',
  parent: angular.element(document.body),
  targetEvent: ev,
})
$mdDialog.show(confirm).then(function(answer) {
  $scope.status = answer;
  $scope.codeRunningBeforeResolve = 'code only runs after resolve';
});

You can see how you'd handle multiple buttons and getting responses other than just OK or Cancel.

Upvotes: 1

A G
A G

Reputation: 22577

You can use a custom template for your confirm dialog.

var confirm = $mdDialog.confirm({
      controller: DialogController,
      templateUrl: 'dialog1.tmpl.html',
      parent: angular.element(document.body),
      targetEvent: ev,
    })
    $mdDialog.show(confirm).then(function() {
      $scope.status = 'Confirm resolved';
      $scope.codeRunningBeforeResolve = 'code only runs after resolve';
    });

Codepen

Upvotes: 4

Related Questions