I'm looking for a way to override ng-submit so that it performs some functions before evaluating/running the expression it contains. For example, I would like to do the following.
1) Set all fields dirty (or perhaps touched) so that all fields are validated even if the user has skipped over them.
2) Check that all fields validate. If not then don't continue.
3) If any fields are invalid then scroll the first invalid field and focus it.
I have found a few directives that do some of this, some create new element directives but none actually override/extend ngSubmit so I'm wondering if this is possible?
First, an element need not be "touched" for validation to work (that's about point #1). For example, this would invalidate the input, given
$scope.test = "abcd";
and:Second, #2 is easily achieved with
form.$valid
:If pre-submit logic is more complicated then this, it could/should be done in the controller, for example, in the
onSubmit()
function.But, if your pre-submit logic is View-related (as opposed to ViewModel-related) - and scrolling is View-related - then you could create another
ngSubmit
directive with higher priority and prevent default submit event handling:Demo
EDIT:
Using
pre
-link is important here due to order of link function executions. The order of execution is:So, the use of higher priority and
pre
-link ensures that this directive registerselement.on("submit", ...)
before the built-inngSubmit
does it, so it can have a first go at event handling.