angularjs父ng表单有效,即使指令ng表单无效

angularjs父ng表单有效,即使指令ng表单无效,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我已经编写了一个从范围字段生成输入字段的指令,一切正常,除了父ng表单保持无效,即使指令中的ng表单无效 以下是我检查表单状态的方式: <ng-form name="parentForm" class="form-horizontal"> <form-field ng-model="input.name" field="fields[0]" ng-change="changed(input.name)"></form-field> <fo

我已经编写了一个从范围字段生成输入字段的指令,一切正常,除了父ng表单保持无效,即使指令中的ng表单无效

以下是我检查表单状态的方式:

<ng-form name="parentForm" class="form-horizontal">
    <form-field ng-model="input.name" field="fields[0]" ng-change="changed(input.name)"></form-field>
    <form-field ng-model="input.age" field="fields[1]"></form-field>
    <pre> parent form: valid : {{parentForm.$valid}}</pre>
</ng-form>
我想问题是我需要编译父元素而不是元素本身来进行验证,但不确定如何进行验证

// Instead of this:
element.replaceWith($compile(template)(scope));

// Which is equivalent to this:
var linkFunc = $compile(template);   // compiling
var newElem  = linkFunc(scope);      // linking
element.replaceWith(newElem);        // inserting

// You should do this:
var newElem = angular.element(template);   // creating
element.replaceWith(newElem);              // inserting
$compile(newElem)(scope);                  // compiling + linking
                                           // (could be done in 2 steps
                                           //  but there is no need)

根据上的文档,有一个
$addControl()
方法用于:

在表单中注册控件。
使用ngModelController的输入元素在链接时会自动执行此操作

这给了我们一个提示,“
ng model
ed”元素将处理其链接函数中的所有内容,只要我们给它们机会。给他们机会(在此上下文中)意味着他们应该能够在链接时找到其父元素
ngForm
元素。
您已经(相当心胸狭窄地)剥夺了他们的这种权利,首先编译链接它们,然后才将它们插入DOM(真丢脸)

一旦知道原因,解决方法就很简单:
您需要先将它们插入DOM,然后链接它们。
例如:

另请参见此

      element.replaceWith($compile(template)(scope));
// Instead of this:
element.replaceWith($compile(template)(scope));

// Which is equivalent to this:
var linkFunc = $compile(template);   // compiling
var newElem  = linkFunc(scope);      // linking
element.replaceWith(newElem);        // inserting

// You should do this:
var newElem = angular.element(template);   // creating
element.replaceWith(newElem);              // inserting
$compile(newElem)(scope);                  // compiling + linking
                                           // (could be done in 2 steps
                                           //  but there is no need)