2015-10-05 46 views
0

所以我想向表格內的表添加額外的列。添加列本身並不困難,但我不知道如何去設置他們的ng模型。將具有特定ng模型的新列添加到HTML表

這是我當前的代碼: (HTML)

<button ng-click="add()" type="button">+ column</button> 
     <table> 
      <thead id="inputtablehead"> 
       <th class="theadlabel">(in 1.000 EUR)</th> 
       <th>{{startyear}}</th> 
       <th class="NBBCodesHeader">NBB Codes</th> 
       <th>Source</th> 
      </thead> 
      <tbody class="input"> 
       <tr> 
        <td>number of months</td> 
        <td> 
         <input ng-model="input{{startyear}}.NumberMonths" type="text" class="{{startyear}}" required> 
        </td> 
         <td class="NBBCodes"></td> 
       </tr> 
       <tr> 
        <td>Fixed assets</td> 
        <td> 
         <input ng-model="input{{startyear}}.FixedAssets" class="{{startyear}}" type="text" required> 
        </td> 
        <td class="NBBCodes">20/28</td> 
       </tr> 
       <tr> 
        <td>Inventory</td> 
        <td> 
         <input ng-model="input{{startyear}}.Inventory" class="{{startyear}}" type="text" required> 
        </td> 
        <td class="NBBCodes">3</td> 
       </tr> 
</table> 

(JS)

angular.module("inputFields", []).controller("MyTable", function ($scope) { 
    $scope.startyear = new Date().getFullYear(); 
    var nextyear = new Date().getFullYear() - 1; 
    $scope.add = function() { 
     $(".NBBCodesHeader").before("<th>"+nextyear+"</th>"); 
     $(".input .NBBCodes").before('<td><input class='+nextyear+' type="text" required></td>'); 
     nextyear--; 
    }; 
    }); 

所以在我JS的<input class='+nextyear+' type="text" required>應該成爲像<input ng-model="input'+nextyear+'.NumberMonths" class='+nextyear+' type="text" required>明年加入的<td>元素'月數'行。

我正在考慮給ea行添加一個NumberMonths形式的id,然後在添加列時查找id。

所以我的問題是:這是一個有效的方式來做到這一點,我將如何得到這個ID?或者我是否過度這樣做,有沒有更簡單的方法來做到這一點?

回答

0

使用標準javascript []變量屬性名稱的對象表示法。

<input ng-model="input[startyear].Inventory" 
0

您不應該從控制器進行DOM操作。使用AngularJS時,這不是一個好習慣。要記住的一個好規則是:不要使用jQuery。開始使用AngularJS時,這是一個常見的錯誤。而且,如果您完全確定需要修改DOM,請始終從指令開始。

關於你的問題,也許你可以根據你的解決方案在你的控制器(一個Javascript對象)中創建一個數據結構,並通過模板中的ng-repeat來呈現它。這樣,如果您修改對象(添加新列),模板將自動更新。

相關問題