【问题标题】:Detect $mdDialog close while pressing ESC按下 ESC 时检测 $mdDialog 关闭
【发布时间】:2017-01-14 06:12:06
【问题描述】:

我有一个带有输入字段的 $mdDialog。在关闭 $mdDialog 之前,会保存输入字段的内容。因此,当用户按下“关闭”按钮时,会调用一个函数来对数据执行一些操作并保存它们。但是,我无法检测到 $mdDialog 在 ESC 上的关闭。是否可以在 $mdDialog 控制器中使用 ESC 检测关闭事件?

这里是示例代码。 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>

【问题讨论】:

    标签: angularjs angularjs-material


    【解决方案1】:

    你应该使用promise api。

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

    但是带有外部代码的接收器应该与其他机制一起使用,例如通过提供范围。

    var modalScope = $rootScope.$new(true);
    $mdDialog.show({scope: modalScope}).finally(function(){
        $rootScope.draft = modalScope.myText;
    });
    

    【讨论】:

    • 这不能在 $mdDialog 本身的控制器中处理吗?我宁愿不把责任交给启动 $mdDialog 的地方 + 我需要来自控制器的功能
    • 你可以提供范围给modal并尝试监听destroy - scope.$on('$destroy')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 2020-10-08
    • 1970-01-01
    相关资源
    最近更新 更多