Как добавить динамическую строку в таблицу с помощью angularjs

Как jQuery, как я могу добавить динамические строки в таблицу с элементами формы нажатием кнопки с помощью angularjs и как отличить эти элементы формы, такие как имя массива в обычном jquery submit.

<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>

Ответы

Ответ 1

Важно помнить, что при Angular вы не добавляете новые строки в таблицу, а вместо этого изменяете данные модели. При изменении модели изображение автоматически обновится. То, что вы показали в своем примере, - это просто часть HTML-шаблона, что будет делать Angular. Как уже упоминалось, вы не будете изменять эти элементы 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 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; граница: сплошная красная 1px}

"Angular Путь"

Как вы можете видеть, вы не производите прямого изменения DOM. Вы получаете всю искушенную проверку формы без необходимости писать какой-либо реальный код. Контроллер действует исключительно как контроллер, удерживая модель и подвергая различные функции ее области. Вы можете принять это далее по пути Angular, введя службы, которые обрабатывают извлечение и обновление данных, и эти службы затем совместно используются. Возможно, вы уже делаете это в своем коде, но этот код должен работать для вашего конкретного примера без каких-либо дополнительных зависимостей.

Ответ 2

Вы должны отобразить строку, используя 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);
    }
});