【问题标题】:Trigger OK click by pressing enter in ui-bootstrap modal在 ui-bootstrap 模式中按回车触发 OK 点击
【发布时间】:2015-09-15 12:03:14
【问题描述】:

我有一个简单的 ui-bootstrap 模式,其模板如下:

<div class="modal-header">
    <h3 class="modal-title">{{title}}</h3>
</div>
<div class="modal-body">
    {{body}}
</div>
<div class="modal-footer">
    <button class="btn btn-default"
            ng-click="cancel()">
        Cancel
    </button>
    <button class="btn btn-primary"
            ng-click="ok()">
        OK
    </button>
</div>

模态框的默认行为是,如果我按下 Escape,模态框将关闭。同样,如果我按 Enter,我希望 ok() 方法被触发。我该怎么做?

【问题讨论】:

  • 看这个例子gist.github.com/EpokK/5884263。它和普通的 javascript enter 一样,只是包裹在一个指令中。
  • 很好,但我应该在哪里添加指令?
  • 对不起,我错过了关于弹出提交的事实。比您的问题与stackoverflow.com/questions/21633422/… 有关
  • 这些解决方案对我有用,但前提是模态中的某些元素被聚焦,事实并非如此。
  • 无论如何,您需要在模态中获得焦点才能点击进入和提交。

标签: angularjs modal-dialog angular-ui-bootstrap


【解决方案1】:

感谢 Diana R 引导我回答这个问题:

我可以使用 ng-enter 指令,如下所述:https://gist.github.com/EpokK/5884263

这将允许我的模式监听 Enter 键。但是焦点需要在模态中才能发挥作用。所以我还创建了一个我称之为focused的指令:

angular.module('webApp').directive('focused', function ($timeout, $parse) {
    return {
        link: function ($scope, element, attributes) {
            var model = $parse(attributes.focused);
            $scope.$watch(model, function (value) {
                if (value === true) {
                    $timeout(function () {
                        element[0].focus();
                    });
                }
            });

            // set attribute value to 'false' on blur event:
            element.bind('blur', function () {
                if (model && model.assign) {
                    $scope.$apply(model.assign($scope, false));
                }
            });
        }
    };
});

然后我更新我的模态模板,使其看起来像这样:

<div ng-enter="ok()">
    <div class="modal-header">
        <h3 class="modal-title">{{title}}</h3>
    </div>
    <div class="modal-body">
        {{body}}
    </div>
    <div class="modal-footer">
        <button class="btn btn-default"
                ng-click="cancel()">
            Cancel
        </button>
        <button class="btn btn-primary"
                focused="true"
                ng-click="ok()">
            OK
        </button>
    </div>
</div>

由于focused="true" 指令位于带有ng-enter 指令的包装div 内,因此回车键将触发ok() 方法。

【讨论】:

  • 太好了,我能以某种方式帮助你:)
【解决方案2】:

如果您正在寻找更多“开箱即用”的解决方案,我建议您使用ng-focus-if

它的功能要强大得多,但在这里它可以用来聚焦所需的元素。只需标记确认按钮:

 <div class="modal-footer">
    <button class="btn btn-default" ng-click="$dismiss()">
       Cancel
    </button>
    <button class="btn btn-primary" ng-click="$close()" focus-if>
       OK
    </button>
 </div>

现在单击spaceenter 将触发“确定”按钮。您还可以使用tab 按钮进行导航。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-25
    • 2013-08-12
    • 2011-11-12
    • 1970-01-01
    • 2019-10-06
    • 2017-03-26
    • 1970-01-01
    • 2010-09-13
    相关资源
    最近更新 更多