动态地在Angular中向表行添加/删除输入框

时间:2014-11-17 02:05:05

标签: javascript angularjs angular-directive

不知怎的,我无法用角度来理解这个问题 - 我有一个表,想要点击添加行,但是这行应该有空输入框和一个按钮来移除它。

 <tbody>
        <tr>
            <th>Test 1</th>
            <th>200</th>
            <th>Add new row</th>
        </tr>
         //I want to Add this part dynamically everytime when I click on Add new row
                <tr>
                     <td>
                        <input type="text" placeholder="Please Enter the Address">
                    </td>
                    <td>
                        <input type="text" placeholder="Number of Quantity">
                    </td>
         //On Delete it should delete just that particular row
                    <td>Delete</td>
                </tr>

        </tbody>

我创建了plunker http://plnkr.co/edit/DDj5Z99tw1QuN8xlxZ7V?p=preview只是为了展示我想要实现的目标。如果有人能够给出提示或链接我的教程将是伟大的!

1 个答案:

答案 0 :(得分:1)

请看看这个plunker。

http://plnkr.co/edit/ogvezWz6WDwDhCnm2bDU

想法是在末端使用一行,可以控制其可见性。使用 ngRepeat ,您可以迭代显示添加的产品项目。

    <tr ng-repeat="row in rows">
         <td>
            {{row.product}}
        </td>
        <td>
            {{row.quantity}}
        </td>
        <td>
          <button ng-click="deleteRow($index)">Delete</button>
          <button ng-click="addNewRow()">New</button>
        </td>
    </tr>
    <tr ng-show="addrow">
         <td>
            <input type="text" placeholder="Please Enter the Address" ng-model="product"/>
        </td>
        <td>
            <input type="text" placeholder="Number of Quantity" ng-model="quantity"/>
        </td>
        <td><button ng-click="save()">Save</button> <button ng-click="delete()">Delete</button></td>
    </tr>

和控制器代码

angular.module('AddRow', [])
.controller('MainCtrl', [
'$scope', function($scope){
  $scope.rows = [ { "product": "Test 1", "quantity": "200"}];
  $scope.addrow = false;

  $scope.addNewRow = function(){
    $scope.addrow = true;
  };

  $scope.deleteRow = function(index){
    //delete item from array
    $scope.rows.splice(index,1);
  };

  $scope.save = function(){
    //add item to array
    $scope.rows.push({"product": $scope.product, "quantity": $scope.quantity});
    //reset text input values
    $scope.product = "";
    $scope.quantity = "";
    //hide the add new row
    $scope.addrow = false;
  };

  $scope.delete = function(){
    $scope.addrow = false;
  };
}]);