【问题标题】:angularjs parent ng-form valid even when directive ng-form is invalid即使指令 ng-form 无效,angularjs 父 ng-form 也有效
【发布时间】:2014-04-05 08:12:30
【问题描述】:

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

这就是我检查表单状态的方式:

<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>

下面是链接功能

var linkFunction = function (scope, element, attrs) {
    var fieldGetter = $parse(attrs.field);
    var field = fieldGetter(scope);
    var template = input(field, attrs); //genrate the template
    element.replaceWith($compile(template)(scope)); //replace element with templated code
};

我想问题是我需要编译父元素而不是元素本身才能使验证工作,但不确定如何去做

      element.replaceWith($compile(template)(scope));

PLUNKER LINK

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

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

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

    这给了我们一个提示,只要我们给他们机会,“ng-modeled”元素就会处理其链接功能中的所有事情。给他们机会(在这种情况下)意味着他们应该能够在链接时找到他们的父 ngForm 元素。
    你已经(相当心胸狭窄地)剥夺了他们的这项权利,首先编译和链接它们,然后才将它们插入到 DOM (真丢脸)。

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

    // 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)
    

    另请参阅此short demo。

    【讨论】:

      猜你喜欢
      • 2015-11-10
      • 1970-01-01
      • 2015-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多