What I understand
Within Angular 1.3 and higher, I can utilize $submitted
to determine if the specific form has been submitted successfully.
This function works flawlessly when working with a form structured in the following manner:
<form name="myForm" ng-submit="register();" novalidate>
<div>
<input placeholder="First Name" name="name" type="text" ng-model="user.firstName" required />
<span ng-show="myForm.$submitted && myForm.name.$error.required"> First Name is required</span>
</div>
<ng-form name="subForm">
<div>
<input placeholder="Last Name" name="lastName" type="text" ng-model="user.Name" required />
<span ng-show="myForm.$submitted && subForm.lastName.$error.required"> Last Name is required</span>
</div>
</ng-form>
<input type="submit" value="Save" />
</form>
The predicament
However, an issue arises when generating the ng-form dynamically and therefore not knowing the name of the parent form where the ng-form is nested within. This lacks essential information needed to decide when to display a validation error for the input inside the nested ng-form.
Suppose I have a directive intended for use as part of the form.
Index file
<!doctype html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
<script src="lastNameDirective.js"></script>
</head>
<body ng-app="formExample">
<form name="myForm" novalidate>
<input placeholder="First Name" name="name" type="text" ng-model="user.firstName" required />
<span ng-show="myForm.$submitted && myForm.name.$error.required"> First Name is required</span><br />
<last-Name></last-Name>
<br />
<input type="submit" value="Save" />
</form>
</body>
</html>
Directive
angular.module('formExample', [])
.directive('lastName', function() {
return {
restrict: 'E',
templateUrl: 'my-template.html'
};
});
Template
<ng-form name="subForm">
<input placeholder="Last Name" name="lastName" type="text" ng-model="user.Name" required />
<span ng-show="subForm.$submitted && subForm.lastName.$error.required"> Last Name is required</span>
</ng-form>
How can I navigate around this situation? Is there a method to dynamically retrieve the name of the form that my ng-form is enclosed in, or can I somehow monitor a submit on my parent form?
A plunker available for experimentation
Research undertaken so far
I've attempted reviewing RealCrowds Angular-Utilities, currently implemented in my ongoing project (since I've been using Angular 1.2 till now), yet it seems incapable of handling this scenario effectively. (Though conversation has touched on this topic)