Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect $mdDialog close while pressing ESC

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>
like image 665
van Avatar asked Oct 30 '22 20:10

van


1 Answers

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;
});
like image 112
Valery Kozlov Avatar answered Nov 15 '22 09:11

Valery Kozlov