Reputation: 5305
I have a specific problem where I need to add nested form in a form built with angular.
Statically (non-programmatically), I can the do the following:
<form>
...
<ng-form>
<input ng-model="myModel" required>
</ng-form>
...
</form>
And validation error in the nested form invalidates the outer form. Which is exactly what I need.
But I can't seem to do this programmically via a directive. In the template I have the following
<div dynamic-nested-form="">
</div>
And I have the following:
(function () {
angular
.module('controls')
.directive('dynamicNestedForm', dynamicNestedForm);
function dynamicNestedForm($compile) {
return {
restrict: 'A',
link: linkedFunction
};
function linkedFunction($scope, element) {
var nestedForm = angular.element('<ng-form><input ng-model="myModel" required></ng-form>');
element.append($compile(nestedForm)($scope));
}
})();
The form does get injected in the DOM and it is in invalid state, in Chrome element view, I see
<div dynamic-nested-form="" class="ng-scope">
<ng-form
class="ng-pristine ng-scope ng-invalid ng-invalid-required">
<input ng-model="myModel" required=""
class="ng-pristine ng-untouched ng-invalid ng-invalid-required">
</ng-form>
</div>
But outer form does not get invalidated. When the outer form loaded does it not see the inner form?
What am I doing wrong?
Upvotes: 1
Views: 651
Reputation: 5305
Right,
So,
Basically did a little debugging through Angular and it just happens that the nested form could not find the outer form controller. (The outer form controller is needed in ngModelDirective
in its preLink
)
The reason it cannot find it is because this preLink
happens during compile (obviously, it's a preLink
) and my compile was done before the nested form was attached.
So as a solution, instead of compiling before attaching, I do it after, like
var nestedForm = angular.element('<ng-form><input ng-model="myModel" required></ng-form>');
$compile(element.append(nestedForm ).contents())($scope);
Well, I think I am recompiling it.
Anyhoo, this then makes the inner control find the outer form and my problem is solved.
Upvotes: 2