更改ng repeat内部的类以获得输入值



我正在创建一个带有ng repeat的表。这个表有一个输入,人们可以在这里写任何东西。当我想得到所选输入的每个值时,我的问题就来了,因为只得到第一行:

<table class="table">
<thead>
<tr>
<th style="text-align:center">Name</th>
<th style="text-align:center">LastName</th>
<th style="text-align:center;width:200px">Write a funny commentary</th>
<th style="text-align:center">Save</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in myItems">
<th style="font-weight:normal;text-align:center">{{item.name}}</th>
<th style="font-weight:normal;text-align:center">{{item.lastName}}</th>
<th style="font-weight:normal;text-align:center;padding-left: 15px;padding-right: 15px;">
<input type="text" class="form-control" id="theBox">
</th>
<th style="font-weight:normal;text-align:center;padding-left: 15px;padding-right: 15px;">  
<button type="button" class=btn btn-primary ng-click="saveComment(item)">Save</button>
</th>
</tr>
</tbody>
</table>
</tbody>
</table>

我知道输入得到的所有返回值都是相同的id。有一种方法可以获得任何创建行的特定数据吗?甚至我也尝试过querySelectorAll(),但不起作用:

$scope.textOfValue = function(t){
$scope.theValue = t;
//to get the specific data of row
var xandria = document.querySelectorAll("#boxOf"), k, length;
for(k = 0, length = xandria.length; k < length; k++){
xandria[k].classList.add('form-control.x');
}
$scope.getText = document.getElementById('theBox').value;
console.log($scope.getText);
}

有人建议解决方案是AngularJS?中的原型继承?,但我到目前为止还没有完全理解。。。你能帮我举个例子吗?

我使用的是AngularJs和Javascript。

提前Thanx。

您遇到这个问题是因为ng repeat一次又一次地创建具有相同id的输入。您应该使用trackBy来获取索引,并将该索引应用于InputField Id,同时使用循环的索引绑定ng-Model

例如:

<tr ng-repeat="item in myItems track by $index">
<th style="font-weight:normal;text-align:center">{{item.name}}</th>
<th style="font-weight:normal;text-align:center">{{item.lastName}}</th>
<th style="font-weight:normal;text-align:center;padding-left: 15px;padding-right: 15px;">
<input type="text" class="form-control" id="theBox-{{$index}}" ng-model="newInputValue[$index].value>
</th>
<th style=" font-weight:normal;text-align:center;padding-left: 15px;padding-right: 15px;">
<button type="button" class=btn btn-primary ng-click="saveComment(item)">Save</button>
</th>
</tr>

现在,您有了newInputValue的数组,您可以使用索引来访问它。它将创建新对象。此外,如果您试图通过ID访问输入字段,则可以使用$index来获取单个输入字段。

最新更新