如何从angularjs中的表行捕获具有相同名称的ng-model数据?

时间:2015-05-09 19:10:01

标签: javascript angularjs

我创建了一个项目表,只需点击“添加新项目”即可动态增加该项目表。在提交时,我想捕获所有项目(行)信息,以便将其发送到REST服务。

然而,在我的angulajs控制器中,我只能获得第一个项目(第一个表格行),即使通过点击“添加新项目”创建了多个行。

我的代码:

<button id="btnAddNewItem">Add Item</button>
<table id="InputTable" border="0" cellpadding="0" cellspacing="0">
    <thead><tr><th>Item Name</th>
    <th>COD</th>
    <th>EOT</th>
   </tr></thead>
<tbody><tr>
    <td><input type="text" ng-model="item.name"></td>
    <td><input type="text" ng-model="item.COD"></td>
    <td><input type="text" ng-model="item.EOT" id=></td>
    <tr>
 <tbody>
</table>

点击新项目时的逻辑:

 function btnAddNewItem(){
        $("#InputTable tr:last").after(
                "<tr>"+
                "<td><input type='text' ng-model='item.name'></td>"+
                "<td><input type='text' ng-model='item.COD'></td>"+
                "<td><input type='text' ng-model='item.EOT'></td>"+
                "<td><img src='images/delete.png' class='btnExcluir'/></td>"+
        "</tr>");
        return false;
    };

angularjs代码在这里获取项目数据。这仅显示存在多行的第一行。

var myModule = angular.module('MyApp',[]);
myModule.controller('MyCtrl', function($scope, $http) {
    $scope.items[];
    $scope.simulate = function(item) {
        $scope.items.push(item);
        alert($scope.items.length); --returns 1
    };
    });

我实际上将所有行绑定到相同的ng-model名称。

我们是否需要为每个行列维护唯一的ng-model名称?

1 个答案:

答案 0 :(得分:2)

你需要使用$ compiler服务或.. ngRepeat,如果我是你,我会使用它。

<button ng-click="addNewItem()">Add Item</button>
<table id="InputTable" border="0" cellpadding="0" cellspacing="0">
    <thead><tr><th>Item Name</th>
    <th>COD</th>
    <th>EOT</th>
   </tr></thead>
<tbody><tr ng-repeat="item in items">
    <td><input type="text" ng-model="item.name"></td>
    <td><input type="text" ng-model="item.COD"></td>
    <td><input type="text" ng-model="item.EOT" id=></td>
    <tr>
 <tbody>
</table>



var myModule = angular.module('MyApp',[]);
myModule.controller('MyCtrl', function($scope, $http) {
    $scope.items = [];
    $scope.addNewItem = function() {
        $scope.items.push({});
    };
});