2013-06-30 63 views
2

我建立一個SPA,人們可以在添加錶行使用$索引按鈕點擊:爲NG-模型

<!-- Table --> 
<table> 
    <tr> 
    <th>Lieferscheinnummer</th> 
    <th>Stück</th> 
    </tr> 

    <tr ng-repeat="position in positions"> 
    <td><input type="text"></td> 
    <td><input type="text"></td> 
    </tr> 
</table> 

<!-- button --> 
<span ng-click="addPosition()"></span> 

控制器

$scope.positions = ['1']; 
$scope.addPosition = function(){ 
    $scope.positions.push($scope.positions.length + 1); 
} 

現在我要申請一個唯一的ng-model到每個行的每個<td>,以便將給定的輸入發送到我的數據庫。

我搜索了一個解決方案,並絆倒了ng-repeat$index。 不幸的是,$index似乎是元素屬性是不可用:

<tr ng-repeat="position in positions"> 
    <td><input type="text" ng-model="{{$index +1}}"></td> <!-- does not work --> 
    <td><input type="text"></td> 
</tr> 

我將如何運用獨特ng-model每一行,而使用ng-repeat

回答

1

你可以改變你的模型。目前,您正在使用ng-repeat之類的計數器。你有一個存儲元素的模型 - 你不使用元素,只是利用列表中元素的數量並循環多次。

你可以做的是有一個獨特的模型本身的列表。

考慮到您在表格中使用它,每個條目都可能有一個ID字段來唯一標識每一行。

因此,你的模型將是這個樣子:

//Will contain the data entered in the table 
$scope.tableData = [ 
    { 
     id: 1, 
     data: "" 
    }, 
    { 
     id: 2, 
     data: "" 
    } 
]; 

//Will keep track of the last used ID 
$scope.currentId = 2; 

//Will add a record to the table each time it is called 
$scope.addRecord = function() { 
    var newRecord = { 
     id: $scope.currentId++; 
     data: "" 
    }; 
    $scope.tableData.push(newRecord); 
}; 

在您看來,您現在可以使用tableData遍歷實際數據本身,而不是記錄的計數:

<tr ng-repeat="entry in tableData"> 
    <td> 
     <input type="text" ng-model="entry.data"> 
    </td> 
</tr> 

對於其他輸入,您可以簡單地爲每條記錄添加另一個屬性。 ng-repeat將爲每條記錄創建一個範圍,因此entry.data將始終指向位於該行的記錄的data屬性。

注意:對於ID,您可能需要使用另一種方法爲大量記錄生成唯一ID。簡單地增加計數器並不是最好的方法。

+0

這太好了,非常感謝! – Sprottenwels