简体   繁体   English

如何使用angularjs向表中添加动态行

[英]How to add dynamic row to a table using angularjs

Like jQuery, How can I add dynamic rows to a table with form elements in a button click using angularjs and How to differentiate these form elements like array name in normal jquery submit. 像jQuery一样,如何使用angularjs在按钮单击中使用表单元素向表中添加动态行,以及如何在常规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>

It is important to remember that, with Angular, you are not adding new rows to the table but are, instead, modifying the data of the model. 重要的是要记住,使用Angular,您不是要向表中添加新行,而是修改模型的数据。 The view will update automatically when the model changes. 模型更改时,视图将自动更新。 What you have shown in your example is merely the HTML template portion of what Angular is going to do. 您在示例中显示的仅仅是Angular将要执行的HTML模板部分。 As mentioned, you will not be modifying these DOM elements but instead should be manipulating the model. 如前所述,您不会修改这些DOM元素,而应该操纵模型。 So here are the steps I would suggest: 所以这是我建议的步骤:

Create a controller for your table 为您的表创建一个控制器

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"); }
  }

Display the data with your HTML 使用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>

Optionally add CSS to display when fields are valid/invalid (可选)添加CSS以在字段有效/无效时显示

input.ng-invalid { background-color: #FEE; input.ng-invalid {background-color:#FEE; border: solid red 1px } 边框:纯红色1px}

The "Angular Way" “角度方式”

As you can see, you are doing no direct modification of the DOM whatsoever. 如您所见,您不会直接修改DOM。 You get all the baked-in goodness of form validation without having to write any real code. 无需编写任何实际代码即可获得表单验证的所有优点。 The controller acts purely as a controller by holding the model and exposing various functions to its scope. 控制器通过保持模型并将各种功能暴露给其范围来纯粹作为控制器。 You could take this further down the angular path by injecting services which handle retrieving and updating the data, and those services are then shared. 您可以通过注入处理检索和更新数据的服务来进一步沿着角度路径,然后共享这些服务。 Perhaps you already do this in your code, but this code should work for your specific example without any additional dependencies. 也许您已在代码中执行此操作,但此代码应适用于您的特定示例,而不需要任何其他依赖项。

You should render the row using ng-repeat , as such: 您应该使用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>

where this is how your controller should look like: 这是你的控制器应该是这样的:

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);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM