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:
<input ng-model="test" ng-maxlength="3">
Second, #2 is easily achieved with form.$valid
:
<form name="form1" ng-submit="form1.$valid && onSubmit()">
...
</form>
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:
.directive("ngSubmit", function() {
return {
require: "?form",
priority: 10,
link: {
pre: function(scope, element, attrs, form) {
element.on("submit", function(event) {
if (form && !form.$valid) {
event.stopImmediatePropagation();
event.preventDefault();
// do whatever you need to scroll here
}
})
}
}
}
});
Demo
EDIT:
Using pre
-link is important here due to order of link function executions. The order of execution is:
1. pre-link of parent or higher priority directive
2. pre-link of child or lower priority directive
3. post-link of child or lower priority directive
4. post-link of parent or higher priority directive
So, the use of higher priority and pre
-link ensures that this directive registers element.on("submit", ...)
before the built-in ngSubmit
does it, so it can have a first go at event handling.