2013-06-30 47 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