4

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.

Iulia Mihet
  • 650
  • 1
  • 10
  • 34

2 Answers2

4

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

A G
  • 21,087
  • 11
  • 87
  • 112
  • Thank you for your answer, Aseem! This is what I did, I was approaching the solution in a very restrictive manner (no thinking that I can customize the $mdDialog). – Iulia Mihet May 11 '16 at 12:48
  • Also, very important: when referencing the controller which is defined in another file, it should be referenced as string (so, 'DialogController'). Otherwise, AngularJS will give an UnknownProvider error. – Iulia Mihet May 11 '16 at 14:08
1

@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.

Mike Feltman
  • 5,160
  • 1
  • 17
  • 38