I recently developed an AngularJS directive that includes a form. This form consists of a required text field along with two additional child forms. Each child form also contains a required text field.
The distinguishing factor between the two child forms lies in how I implemented them:
- The first child form is compiled and added to a div.
- The second child form is directly inserted into the template of the directive.
Interestingly, when the second child form is invalid, it renders the entire outer form invalid as well, which was my intended behavior. However, if the first child form (the one I manually compiled) becomes invalid, it does not affect the validity of the parent form. Why is this the case?
https://i.sstatic.net/HtuRG.png
var app = angular.module('plunker', []);
app.component('generator', {
template: "<ng-form name=\"outterForm\">" +
"<input name=\"out\" ng-model=\"$ctrl.out\" ng-minlength=\"5\" ng-required=\"true\" type=\"text\" />" +
"<div id=\"component-container\"></div>" +
"<my-text></my-text>" +
"<div>Valid outterForm: {{outterForm.$valid}}</div>" +
"</ng-form>",
controller: function($compile, $scope, $document) {
var componentContainer = $document.find('#component-container');
var template = "<my-text></my-text>";
var childScope = $scope.$new();
var result = componentContainer.append(template);
$compile(result)(childScope);
}
});
app.component('myText', {
template: "<ng-form name=\"innerForm\"><input name=\"name\" ng-model=\"$ctrl.name\" ng-minlength=\"5\" ng-required=\"true\" type=\"text\" />Valid innerForm: {{innerForm.$valid}}</ng-form>"
});
Check out the live Plunker demo here: