Reputation: 393
I'm creating a table with ng-repeat. This table have an input where people can write anything. My problem comes when i wanna get each value of the selected input, 'cause only gets the very first row:
<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>
I know that the input is getting the same id for all the returned values. There's a way to get the specific data of any created row? Even i've tried with querySelectorAll()
but is not working:
$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);
}
Someone suggest that the solution is here prototypical inheritance in AngularJS?, but i'm so far to understand it at all... can you help me with an example, please?
I'm using AngularJs and Javascript.
Thanx in advance.
Upvotes: 0
Views: 91
Reputation: 8478
You are running into this problem because ng-repeat is creating the input with same id again and again.
You should use trackBy
to get the index and apply that index for the InputField Id and at the same time bind your ng-Model
using the index of loop.
Ex:
<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>
Now,you have array of newInputValue
, You can access it using index .It will create new object. Also if you try to access the input field by ID, You can use $index
to get the individual input field.
Upvotes: 1