I've made a directive for a special type of submit button that watches when its form is submitted, and then that buttons is disabled and gets a nice animated progress bar.
This all works fine when the form is submitted by pressing the submit button or pressing enter in one of the fields, the onsubmit handler is called just fine.
The problem: in one of my forms I have a textarea which I want to submit when the user presses the enter key. So I made an onEnter directive that just looks for the right key press and then executes a function.
<form name="form" ng-submit="controller.submit()">
<textarea ng-model="controller.newMessage.content"
autofocus on-enter="controller.submit()"></textarea>
<progress-button type="submit">Post</progress-button>
</form>
The problem of course is that this doesn't trigger the onsubmit handler, and thus the button isn't disabled or anything. How could I solve this? I've tried something like document.form.submit()
, but that submits the form in the old fashioned HTML way, of course bypassing all Angular / JS code and handlers. Should I find the submit button and simulate a click? That feels very hackish too.
Sadly $scope.form
is very useless, nothing there to submit it.
Edit 1: Just so the problem is clear: yes, the controller.submit() function is called just fine via the on-enter directive. However, the form doesn't get a submit event which my button is listening for.
Edit 2: Here is a gist with my button directive. The button currently needs a "pb-click"
attribute, or its form needs a "pb-submit"
attribute. Those functions need to return a promise.
Moving this logic to a scope variable that's set from these functions might not be a big deal since that means we can use standard ng-click
and ng-submit
, don't need to return promises, etc. On the other hand, if you have 5 buttons on one page you then need to create 5 scope variables. Not the best idea either. Or keep using pb-click
and for forms use a scope variable?
I've managed to achieve this by adding $submit
method to FormController:
module.directive('form', function($parse) {
return {
require: 'form',
restrict: 'E',
link: function(scope, element, attrs, formController) {
formController.$submit = $parse(attrs.ngSubmit);
}
};
});
You can then invoke form's ng-submit
expression by calling $scope.myForm.$submit($scope)
from the controller.
The $parse
in aikoven's answer didn't seem to be working for me, so I modified it to use scope.$eval
instead. I also added form.$setSubmitted()
so the form properly gets the .ng-submitted
class after you submit it.
app.directive('form', function() {
return {
require: 'form',
restrict: 'E',
link: function(scope, elem, attrs, form) {
form.$submit = function() {
form.$setSubmitted();
scope.$eval(attrs.ngSubmit);
};
}
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With