0

Hi I have follow code:

<form ng-submit="ctrl.commitEdit(sign)">
    <input ng-model="sign.Value">
    <input ng-model="sign.Date">
    <textarea ng-model="sign.Comment"></textarea>
    <select ng-model="sign.Property"></select>
    <button type="submit">Save</button>
</form>

With my form around my components I tried to save my edits in two ways (in my form I call in the ng-submit a method from my controller, which saves my edits):

  • With the click on my button, which has the type "submit", it calls the function in the ng-submit of my form. This works correctly! It saves
  • Then I also would like to save with pressing the "enter" on my keyboard. Thats why I used the form an ng-submit with my button of type submit. This works only, when I change something in my inputs and the focus is there! When I change something in my textarea and I press "enter", it makes a break. When I change something in my dropdown and then press "enter", it opens the dropdown again.

So I would like to save with pressing "enter" in every way, on the input, select and textarea. How can I do this?

Thanks

webta.st.ic
  • 4,781
  • 6
  • 48
  • 98

1 Answers1

1

All you need to do is use ngKeyup.

https://docs.angularjs.org/api/ng/directive/ngKeyup

Just bind it with enter key code which is 13 and call your function

Moreover here is a directive you can implement for your purpose.

app.directive('ngEnter', function() {
        return function(scope, element, attrs) {
            element.bind("keydown keypress", function(event) {
                if(event.which === 13) {
                        scope.$apply(function(){
                                scope.$eval(attrs.ngEnter);
                        });

                        event.preventDefault();
                }
            });
        };
Tirthraj Barot
  • 2,671
  • 2
  • 17
  • 33
  • Hi and thanks for your answer. But why works the ng-submit fine with my inputs and with my textarea and dropdown not? When I write a value in one of my inputs and press "enter", it calls the function in my controller an saves it correctly. When I do the same in my textarea it just makes a new line in the textarea. The same for my select, it openes the dropdown again and shows the items. Is this because of the default behavoir of the browser by pressing enter in the select or textarea? I would be happy if I could use the ng-submit on the select and textarea as on the input... – webta.st.ic May 18 '16 at 09:17
  • The ng-submit is nice, because I can implement it in one tag (form) once and just give the type "submit" on my button within of my form. So it's easy to care for the code. I once call the function... – webta.st.ic May 18 '16 at 09:20