how to remove the row of the table containing textbox by clicking the respective remove button

后端 未结 1 342
花落未央
花落未央 2021-01-28 08:31

I have an add button which adds the row containing texbox. However I want to remove the row of the table by clicking the respective remove button. The view page code is like thi

相关标签:
1条回答
  • 2021-01-28 09:23

    First, make it easier to iterate through the rows. You want N rows, and each row should have two pieces of information: a name and an address.

    So don't use two arrays. Use one array, of rows, where each row has a name and an address:

    $scope.rows = [
      {
        name: 'name 1',
        address: 'address 1'
      },
      {
        name: 'name 2',
        address: 'address 2'
      }
    ];
    

    To add a row, all you need is

    $scope.rows.push({
      name: '',
      address: ''
    });
    

    To iterate on the rows, all you need is

    <tr ng-repeat="row in rows">
      <td>{{$index+1}}</td>
      <td><input type="text" ng-model="row.name" /></td>
      <td><input type="text" ng-model="row.address" /></td>
      <td><input type="button" ng-click="removeRow(row)" value="Remove" /></td>
    </tr>
    

    As you see, you need to pass what row to remove in your removeRow function.

    And to remove the row, all you need is to find its index in $scope.rows, and remove that index:

    $scope.removeRow = function(row) {
      var index = $scope.rows.indexOf(row);
      $scope.rows.splice(index, 1);
    }
    

    I don't know exactly what each row is supposed to represent. I guess it might be a user, for example, so feel free to rename rows to users, and row to user. Naming things, and having a good, correct model, is the key. Your page displays a table of users. Not two tables of names and addresses.

    0 讨论(0)
提交回复
热议问题