如何使用AngularJS向表格添加动态行

13

我该如何使用AngularJS在按钮单击时向表格添加动态行和表单元素,类似于jQuery?同时,在提交表单时,如何像正常的 jQuery 提交一样区分这些表单元素,例如数组名称。

<tr>
    <td style="text-align:center">1</td>
    <td>
         <input type="text" class="form-control"  required ng-model="newItem.assets">
    </td>
    <td>
        <select ng-model="newItem.type" class="form-control">
            <option value="Rent" ng-selected="'Rent'">Rent</option>
            <option value="Lease">Lease</option>
        </select>
    </td>
    <td>
        <input type="text" class="form-control"  required ng-model="newItem.amount" />
    </td>
    <td>
        <select ng-model="newItem.calculation_type" class="form-control">
            <option value="Daily" ng-selected="'Daily'">Daily</option>
            <option value="Monthly">Monthly</option>
            <option value="Yearly">Yearly</option>
        </select>
    </td>
    <td>
        <input type="text" class="form-control"  required ng-model="newItem.total_amount" />
    </td>
</tr>
2个回答

18

记住,在Angular中,你不是在向表格中添加新行,而是修改模型的数据。当模型改变时,视图会自动更新。你在示例中展示的仅是Angular将要执行的HTML模板部分。如前所述,你不应该修改这些DOM元素,而应该操作模型。因此,我建议按照以下步骤进行:

为你的表格创建一个控制器

app.controller('CostItemsCtrl', [ '$scope', function($scope) {
  // the items you are managing - filled with one item just as an example of data involved
  $scope.items = [ { assets: 'My assets', type: 'Rent', amount: 500, 'calculation_type': 'Daily', total: 0}, ... ];
  // also drive options from here
  $scope.assetTypes = [ 'Rent', 'Mortgage' ];
  $scope.calcTypes = [ 'Daily', 'Monthly', 'Yearly' ];

  // expose a function to add new (blank) rows to the model/table
  $scope.addRow = function() { 
    // push a new object with some defaults
    $scope.items.push({ type: $scope.assetTypes[0], calculation_type: $scope.calcTypes[0] }); 
  }

  // save all the rows (alternatively make a function to save each row by itself)
  $scope.save = function() {
    // your $scope.items now contain the current working values for every field shown and can be parse, submitted over http, anything else you want to do with an array (like pass them to a service responsible for persistance)
    if ($scope.CostItemsForm.$valid) { console.log("it's valid"); }
  }

用HTML显示数据

<form name="CostItemsForm" ng-controller="CostItemsCtrl">
<table>
<tr><th>Assets</th><th>Type</th><th>Amount</th><th>Calculation</th><th>Total</th></tr>
<tr><td colspan="5"><button ng-click="addRow()">Add Row</button></td></tr>
<tr ng-repeat="item in items">
  <td><input required ng-model="item.assets"></td>
  <td><select ng-model="item.type" ng-options="type for type in assetTypes"></select></td>
  <td><input required ng-model="item.amount"></td>
  <td><select ng-model="item.calculation_type" ng-options="type for type in calcTypes"></td>
  <td><input required ng-model="item.total"></td>
</tr>
<tr><td colspan="5"><button ng-click="save()">Save Data</button></tr>
</table>
</form>

可以选择添加CSS以在字段有效/无效时显示

input.ng-invalid { background-color: #FEE; border: solid red 1px }

“Angular方式”

正如您所看到的,您根本不需要直接修改DOM。您可以获得所有内置的表单验证好处,而无需编写任何实际代码。控制器仅充当控制器,通过保存模型并向其范围公开各种函数来实现此目的。您可以通过注入处理检索和更新数据的服务,并共享这些服务,将其进一步向angular路径下引导。也许您已经在您的代码中这样做了,但是这段代码应该可以在不添加任何其他依赖项的情况下适用于您的特定示例。


3

您应该使用ng-repeat来渲染行,例如:

<form ng-submit="onSubmit(newItem)">
    <table>
    <tr>
        <td style="text-align:center">1</td>
        <td>
             <input type="text" class="form-control"  required ng-model="newItem.assets">
        </td>
        <td>
            <select ng-model="newItem.type" class="form-control">
                <option value="Rent" ng-selected="'Rent'">Rent</option>
                <option value="Lease">Lease</option>
            </select>
        </td>
        <td>
            <input type="text" class="form-control"  required ng-model="newItem.amount" />
        </td>
        <td>
            <select ng-model="newItem.calculation_type" class="form-control">
                <option value="Daily" ng-selected="'Daily'">Daily</option>
                <option value="Monthly">Monthly</option>
                <option value="Yearly">Yearly</option>
            </select>
        </td>
        <td>
            <input type="text" class="form-control"  required ng-model="newItem.total_amount" />
        </td>
    </tr>
    <tr ng-repeat="row in rows">
        <td>{{row.assets}}</td>
        <td>{{row.selected}}</td>
        <td>{{row.amount}}</td>
        <td>{{row.calculation_type}}</td>
    </tr>
    </table>
</form>

以下是你的控制器应该看起来的样子:

angular.module('angularSimpleApp').controller('MyCtrl', function ($scope) {
    $scope.newItem = ''; // represents the models in the form
    $scope.rows = [];
    $scope.onSubmit = function(obj) {
        $scope.products.push(obj);
    }
});

但是我如何通过按钮点击添加更多带有输入框的行,就像第一行那样呢?添加更多 - Anshad Vattapoyil
2
当更新模型时,Angular指令将负责将附加行添加到接口中。这是一个工作示例http://plnkr.co/edit/VJSO588pXYBc72mC0sfg?p=preview - Casey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接