Validation in Angular can work even without physically interacting with an element, as demonstrated in point #1. For instance, setting $scope.test = "abcd";
would invalidate the input if it is limited to a maximum length of 3 characters:
<input ng-model="test" ng-maxlength="3">
To achieve point #2, one can simply utilize form.$valid
:
<form name="form1" ng-submit="form1.$valid && onSubmit()">
...
</form>
If there's more complex pre-submit logic involved, it should be handled within the controller, such as in the onSubmit()
function.
However, when the pre-submit logic pertains to the View rather than the ViewModel - like scrolling - creating a custom ngSubmit
directive with higher priority can intercept the 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();
// implement necessary scrolling actions here
}
})
}
}
}
});
View Demo
EDIT:
The use of pre
-link is crucial in this context due to the order of link function executions. The sequence of execution follows:
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
By leveraging higher priority and pre
-link, this directive can register element.on("submit", ...)
before the built-in ngSubmit
, ensuring precedence in event handling.