0

我有一個包含一個字段集的表單,Form可以有不同數量的這個字段集,所以我在表單中增加了一個更多的按鈕。可能會出現表單沒有字段集的情況。爲了滿足這些要求,我需要指令繼承。 fieldset指令將被添加到按鈕單擊事件上。 Fieldset有一個模板,但實際的輸入字段HTML字符串是在頁面加載時從服務器傳入的。因此我需要通過添加具有不同id的輸入框來即時完成字段集,然後將此字段集添加到表單中。雙向數據綁定在孤立的子指令

爲了更好地解釋這種情況,我縮小了我的實現並創建了下面的代碼片段,這裏是plunker

在縮小的情況下,頁面加載時只存在form-Dir指令。該指令具有增加id的字段按鈕。

<body ng-app="mainApp" ng-controller="MainCtrl"> 
     <div form-dir this-page="page" bind-field-id = "fieldId" bind-first-name="firstName" > 
      This is {{page}} page 
      <button class='btn-add'> add isolated fields </button> 
      <div class='field'> 

      </div> 
     </div> 
</body> 

腳本

var app = angular.module('mainApp', []); 

app.controller("MainCtrl", function($scope){ 
    $scope.page = "Demo" 
    $scope.fieldId = "2" 
    $scope.firstName = "John" 


}); 

app.directive("formDir", function($compile) { 

    return { 
     restrict:'A', 
     transclude: false, 
     scope:{ 
      page:"=thisPage", 
      id:"=bindFieldId", 
      firstName:"=bindFirstName" 
     }, 
     link : function(scope, element, attrs){ 
      scope.page = 'demo2'; 

      element.find('.btn-add').bind('click', function(e){ 
       var field = angular.element(e.currentTarget).siblings('.field') 

       var newScope = scope.$new(); 

       var ele = '<field-dir bind-field-id = "id" bind-first-name="firstName"></field-dir>'; 

       var directive = $compile(ele)(newScope); 

       field.append(directive); 

       console.log('btn clicked', field) 
      }) 
     } 
    }; 
}); 

app.directive("fieldDir", function() { 

    return { 
     restrict:'AE', 
     transclude: true, 
     replace: true, 
     scope:{ 
      id:"=bindFieldId", 
      firstName:"=bindFirstName" 
     }, 
     template: '<div></div>', 
     link : function(scope, element, attrs){ 

      element.append('<label>{{scope.id}} First Name fields </label>' 
       +' <input type="text" class="textbox" ng-model="firstName">' 
       +' <button class="btn-change">change first name</button>'); 

      element.find('.btn-change').bind('click', function(e){ 
       scope.$apply(function(){ 
        scope.firstName = "Doe"; 
        scope.id = parseInt(scope.id) + 1; 
       }); 


       console.log(scope) 
      }) 

     } 
    }; 
}); 

如果我把labelinput和模板button標籤的代碼將工作;但根據我的情況我需要追加它。我無法弄清楚我做錯了什麼。

回答

0

我想通了。我需要做的是在追加HTML字符串字段之前進行$編譯。

更換

element.append('<label>{{scope.id}} First Name fields </label>' 
+' <input type="text" class="textbox" ng-model="firstName">' 
+' <button class="btn-change">change first name</button>'); 

var r = $compile('<label>{{id}} First Name fields </label>' 
    +' <input type="text" class="textbox" ng-model="firstName">' 
    +' <button class="btn-change">change first name</button>')(scope) 

element.append(r);