【发布时间】:2025-12-03 18:20:02
【问题描述】:
我创建了一个动态添加新行的表。但我无法保存数据。如何创建单独的每行数据以及如何将数据传递给控制器。这是代码。
<table class="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col"> File</th>
<th scope="col">Comments</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in table.rows ">
<td><input type="text" ng-model="rowdata.id"></td>
<td><input type="text" ng-model="rowdata.file"></td>
<td><input type="text" ng-model="rowdata.Comments"></td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-secondary"
ng-click="addNewRow(table)">Add New Row</button>
<button type="button" class="btn btn-primary"
ng-click = "saveData(rowdata)">Save changes</button>
controller.js
.controller('homeController',function($scope){
$scope.table=[{name: "table 1"}];
$scope.table.rows = [{name: "row 1"}];
$scope.counter = 3;
$scope.addNewRow=function(table){
table.rows.push({name: "row " + $scope.counter});
}
$scope.saveData=function(data){
console.log(data);
localStorage.setItem('data',data);
}
})
当我点击保存时,我在控制台中变得未定义。我希望传递行中的数据。一旦我点击保存按钮,数据应该被保存,它应该在表格中反映为不可编辑的字段。
【问题讨论】:
-
您的控制器中没有
rowdata变量。rowdata仅在视图中创建和填充,inside ng-repeat。所以它是在 ng-repeat 为每一行创建的范围内创建的。不在您的控制器范围内。你应该有类似ng-model="row.id"的东西,以便填充table.rowsarray 的每个元素。然后您可以使用$scope.table.rows访问控制器中的数据
标签: angularjs