18

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 :)

Roger Johansson
  • 22,764
  • 18
  • 97
  • 193
  • 1
    Could you show some of your code (and maybe a plunkr or jsfiddle link) I haven't tried this particular combination yet but it sounds like it should work (perhaps there's a dialog option that needs to be set to prevent it from closing itself on keypress and to only close when explicitly closed in code). – shaunhusain Jul 09 '13 at 16:07
  • Found the problem, see above edit – Roger Johansson Jul 09 '13 at 16:18
  • 2
    Cool if you didn't find a similar SO post you should answer your own question and show what went wrong, for future you and everyone else. – shaunhusain Jul 09 '13 at 16:22
  • „specify explicitly that my "cancel" button was of type "button"“… @RogerAlsing made my day :) – xlttj Sep 08 '16 at 12:38

2 Answers2

32

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...

Roger Johansson
  • 22,764
  • 18
  • 97
  • 193
1

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

Sabin Bogati
  • 721
  • 8
  • 11