I've got a nested AngularJS form like so:
<form name="parentForm" ng-submit="submit()">
<input name="parentInput" type="text">
<ng-include src="childForm.html" ng-form="childForm"></ng-include>
<button type="submit">Submit</submit>
</form>
And here's childForm.html
<input name="childInput" type="text">
For reasons unrelated to the question, I can't merge the parent and child forms - they need to be two separate files.
Now, when the user clicks the submit button, validation is correctly applied to both parentForm and childForm. However, only the parent form has it's $submitted flag set to true, which is problematic since I'm using it to trigger the display of certain error messages. I don't want the child form checking if the parent form is $submitted, since they're two separate files. The only option that's occurred to me is having the submit() method call $setSubmitted() on the child form, which is awkward since now the parent form needs to directly reference the child form. Is there a better way to set the child form's $submitted to true?
As an extension of Meeker's solution, you could achieve the $broadcast
implicitly by adding a watch to the parent form:
.directive('form', function() {
return {
restrict: 'E',
require: 'form',
link: function(scope, elem, attrs, formCtrl) {
scope.$watch(function() {
return formCtrl.$submitted;
}, function(submitted) {
submitted && scope.$broadcast('$submitted');
});
}
};
})
.directive('ngForm', function() {
return {
restrict: 'EA',
require: 'form',
link: function(scope, elem, attrs, formCtrl) {
scope.$on('$submitted', function() {
formCtrl.$setSubmitted();
});
}
};
})