问题
From what I can see, the recomended way to handle enter key in dialogs in AngularJS is to place a <form> tag and a submit button inside the dialog.
Fair enough, but if you use Angular-UI and their $dialog service, the form will simply close silently when pressing enter. no way to intercept that. even if you attach handlers to ng-click or ng-submit, the form will just close w/o returning any result.
Is there something else I need to do
[Edit]
Solved it, I had to specify explicitly that my "cancel" button was of type "button". Seems like it defaults to "submit" ?
So there was no real problem except for my html form skills :)
回答1:
To answer my own question. Buttons seems to default to submit(?) and if I explicitly set them to type="button" then they will not trigger postback when pressing enter in an form input field.
<form>
<input type="text" ... />
<button type="button" ng-click=...>Cancel</button>
<button type="submit" ng-click=...>OK</button>
</form>
this way, pressing the enter key in the input field will trigger the ng-click for the OK button.
And as you html hackers have already understood, this had nothing to do with dialogs nor angularjs really, it was a html form issue and my lack of web skills...
回答2:
I believe it's because your "CLOSE" button, is not set to type="button", and I THINK that's the first element that has focus, so when pressing enter, you are entering that button, which by default, will submit the form. Add type="button" and that should solve it.
Also for the record, the latest version of angular material has md-button automatically add type="button" by default (unless you specify type="submit") to avoid this type of situation
来源:https://stackoverflow.com/questions/17551220/angular-ui-dialog-and-form-submit-on-enter-key