簡體   English   中英

在 AngularJS 指令中編譯表單

[英]Compiling form inside AngularJS directive

我寫了一個帶有表單的 AngularJS 指令。 該表單有一個必填的文本字段以及兩個其他表單。 每個子表單都有另一個必需的文本字段。

2個子表單之間的區別在於我如何創建它們:

  1. 第一個子窗體被編譯並附加到一個 div。
  2. 第二個子表單直接包含在指令的模板中。

如果第二個子表單無效,則整個外部表單無效。 這是我所期望的。 但是,如果第一個子窗體(我手動編譯的那個)變為無效,則它對外部父窗體沒有影響。 為什么?

在此處輸入圖片說明

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>"
});

這是正在運行的Plunker:

https://plnkr.co/edit/YfBRY4xPvKgqDtWXFMUi

那是因為在編譯該子表單后還沒有設置子表單的formController $$parentForm 我不知道為什么,我想它需要更深入的知識。

我在不同的編譯階段(preLink、postLink)嘗試$compile()() ) 並得到相同的結果。 但是我幾乎用兩種方法實現了目標:

  • 首先是像這樣直接賦值$$parentForm childScope.innerForm.$$parentForm = scope.outterForm; . 是我的 plunker 示例(注意我將components更改為directives ,因為它們更靈活)。
  • 其次是重新編譯父表單(但這會使手動子表單編譯變得無用)。 是第二個plunker示例。

但! 在這兩種方法中都存在一個巨大的問題——動態設置子表單名稱和模型(應該是這樣,因為您想在多個子表單上使用一個指令)。

在第一種方法中沒有錯誤,但有一個錯誤:當您更改第二個子表單的模型時,它會更改第一個子表單的模型(一旦調整第一個子表單的模型,它就會停止)。

在第二種方法中,一切似乎都很好,但是在后台,每次更改模型時都會發生很多錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM