5

I have a $mdDialog with input fields. Before closing $mdDialog, the content of the input fields is saved. So, when a user press 'close' button, a function is called to perform some operation on data and save them. However, I could not detect closing of $mdDialog on ESC. Is it possible to detect the closing event with ESC in the $mdDialog controller ?

Here is the sample code. Codepen link

angular.module('MyApp', ['ngMaterial'])

.controller('AppCtrl', function($scope, $mdDialog, $rootScope) {
  //$rootScope is used only of this demo
  $rootScope.draft = '  ';

  $scope.showDialog = function(ev) {
    var msgDialog = $mdDialog.show({
      controller: 'DemoDialogCtrl',
      template: "<md-input-container><label>Text</label><input type='text' ng-model='myText' placeholder='Write text here.'></md-input-container><md-button ng-click='close()'>Close</md-button>",
    })

  };


});

(function() {
  angular
    .module('MyApp')
    .controller('DemoDialogCtrl', DemoDialogCtrl);

  DemoDialogCtrl.$inject = ['$scope', '$rootScope', '$mdDialog'];

  function DemoDialogCtrl($scope, $rootScope, $mdDialog) {


    $scope.close = function() {
      //$rootScope is used only of this demo
      // In real code, there are some other operations 
      $rootScope.draft = $scope.myText;

      $mdDialog.hide();
    }

  }
})();
<div ng-controller="AppCtrl" class="md-padding dialogdemoBasicUsage" id="popupContainer" ng-cloak="" ng-app="MyApp">
  <div class="dialog-demo-content" layout="row" layout-wrap="" layout-margin="" layout-align="center">
    <md-button class="md-primary md-raised" ng-click="showDialog($event)">
      Open Dialog
    </md-button>
    <div id="status">
      <p>(Text written in $mdDialog text field must appear here when user closes the $mddialog. User can press close button or press ESC button.
      </p>
      <b layout="row" layout-align="center center" class="md-padding">
                 Draft: {{draft}}
            </b>
    </div>
  </div>
</div>
Kostas Siabanis
  • 2,989
  • 2
  • 20
  • 22
van
  • 633
  • 14
  • 26

1 Answers1

2

You should use promise api.

$mdDialog.show().finally(
   function onModalClose(){

   }
);

But sink with external code should be used with other mechanism, for example by providing scope.

var modalScope = $rootScope.$new(true);
$mdDialog.show({scope: modalScope}).finally(function(){
    $rootScope.draft = modalScope.myText;
});
Valery Kozlov
  • 1,557
  • 2
  • 11
  • 19
  • Can't this be handled in the controller of the $mdDialog itself? I would rather not give the responsibility to the place where the $mdDialog is initiated + I need functions from the controller – Thomas Stubbe Sep 28 '16 at 13:01
  • 1
    you can provide scope to modal and try to listen destroy - scope.$on('$destroy') – Valery Kozlov Sep 28 '16 at 13:10