我在角度js中为模态弹出创建了一个自定义组件。一切正常。现在我想在此实现键盘交互。也就是说,当模态弹出窗口显示消息时,用户应该能够通过按Enter键关闭。
(function () {
"user strict";
var myApp = angular.module("myApp");
myApp.component("ModalDialog", {
bindings: {
show: '=',
title: '=',
type: '=',
okCallback: '&?',
okText: '=?',
cancelCallback: '&?',
cancelText: '=?'
},
replace: true,
transclude: true,
controller: function ($element, $attrs) {
var $ctrl = this;
$ctrl.dialogStyle = {};
if ($attrs.width)
$ctrl.dialogStyle.width = $attrs.width;
if ($attrs.height)
$ctrl.dialogStyle.height = $attrs.height;
if ($attrs.okCallback)
$ctrl.okEnabled = true;
if ($attrs.cancelCallback)
$ctrl.cancelEnabled = true;
$ctrl.hideModal = function () {
$ctrl.show = false;
};
$ctrl.ok = function () {
$ctrl.okCallback();
};
$ctrl.cancel = function () {
$ctrl.cancelCallback();
}
},
template: '<div class="ng-modal" data-ng-show="$ctrl.show">\n' +
'<div class="ng-modal-overlay" ng-click="$ctrl.hideModal()"></div>\n' +
'<div class="ng-modal-dialog" ng-class="{\'warning\' : $ctrl.type.toLowerCase() === \'warning\'}" data-ng-style="$ctrl.dialogStyle">\n' +
'<div class="ng-modal-dialog-header">{{$ctrl.title}}</div>\n' +
'<div class="ng-modal-dialog-content" ng-transclude></div>\n' +
'<div class="ng-modal-dialog-footer ng-button-group">\n' +
'<button data-ng-show="$ctrl.okEnabled" class="ng-button-primary" data-ng-click="$ctrl.ok()">{{$ctrl.okText}}</button>\n' +
'<button data-ng-show="$ctrl.cancelEnabled" class="ng-button-secondary" data-ng-click="$ctrl.cancel()">{{$ctrl.cancelText}}</button>\n' +
'</div>' +
'</div>\n' +
'</div>'
});
})();
HTML
<ng-modal-dialog show='$scope.alertModal.shown' width='400px' data-title='$scope.alertModal.title' data-type="$scope.alertModal.type" ok-callback="$scope.closeAlertModal()" ok-text="$scope.alertModal.okText">
{{$scope.alertModal.message}}
</ng-modal-dialog>
JS
$scope.closeAlertModal = function(){
$scope.alertModal.shown=! $scope.alertModal.shown;
};
提前致谢
答案 0 :(得分:0)
在你的控制器中你必须&#34;听&#34;到keydown活动。
这样的事情:
windowElem.on("keydown", function (event) {
switch (event.which){
// escape key
case 27:
doStuff();
break;
//enter key
case 13:
doOtherStuff();
break;
}
});