【问题标题】:How to save the data of multiple rows of a html table using angular js如何使用angular js保存html表格的多行数据
【发布时间】: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


【解决方案1】:

您只需将$scope.table.rows 保存在您的控制器中,无需将rowdata(不存在)作为参数传递给您的$scope.saveData 函数。

$scope.saveData = function(){
  localStorage.setItem('data', $scope.table.rows);
}

但如果您更喜欢将表格数据作为参数传递,它可能如下所示:

模板

<button class="btn btn-primary"
  type="button"
  ng-click = "saveData(table.rows)">
  Save changes
</button>

控制器

$scope.saveData = function(tableData){
  localStorage.setItem('data', tableData);
}

【讨论】:

    最近更新 更多