AngularJS - Accept a ui.bootstrap modal with ENTER

2019-04-20 18:30发布

问题:

The Issue:
I've been unable to to accept a modal window with the ENTER key

I have modified the default Plunker to show you what I've done since now --> Here

What I have:
Briefly, the ENTER key is recognized by the modal, but it doesn't trigger my function (scope issues, I suspect).

The bad part is that I had to modifiy the template/modal/window, which I would gladly left unspoiled, if possible.

What I would love
I would love to simply put the ng-enter directive in my modal, without modifying the default template

Extra
I've also tried to add the "event 13" to the modal directive, but I couldn't pass any result in the modal.close, so I dropped that road

Any thought?

回答1:

Check my Plunker. You should add ng-enter to "OK" button.

<button class="btn btn-primary" ng-enter="ok();" ng-click="ok()">OK</button>

Maybe you are looking for something more generic, I'm not sure. Then you might consider watchers. But personally I find this better since we don't have any constant watcher which listens modal event.



回答2:

I have found that it is easiest just to add the enter event handler in the controller of the modal:

var text = "This is the text in the modal";
var modalPromise = $modal.open({
    template:
    '<div class="modal-body">' +
    '<button class="close" ng-click="$dismiss(\'×\')">×</button>'+
    '<h3 ng-bind="body"></h3>'+
    '</div>'+
    '<div class="modal-footer">'+
    '<button class="btn btn-primary" ng-click="$close(\'ok\')">OK</button>'+
    '<button class="btn btn-warning" ng-click="$dismiss(\'cancel\')">Cancel</button>'+
    '</div>',
    controller: function ($scope, $document) {
        $scope.body = text;

        var EVENT_TYPES = "keydown keypress"
        function eventHandler(event) {
            if (event.which === 13) {
                $scope.$close('ok');
            }
        }
        $document.bind(EVENT_TYPES, eventHandler);
        $scope.$on('$destroy', function () {
            $document.unbind(EVENT_TYPES, eventHandler);
        })
    }
}).result;


回答3:

AngularJS support this be default.

Add a <form> tag in your template (modal.html) and add ng-submit directive e.g.

<form name="questionForm" ng-submit="ok()">
  <div class="modal-header">
    <h3 class="modal-title">{{title}}</h3>
  </div>
  // the rest of the code here
</form>