0

I have created an item table which can be dynamically increased on click of 'Add New Item'. On submission I want to capture all items(rows) info for sending it to REST service.

However in my angulajs controller, I can get only the first item (first table row) even though there are multiple rows created by clicking on 'Add New Item'.

My code:

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

Logic when click on new item:

 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 code is here to get items data. This shows only the first row even multiple rows exist.

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

I am actually binding all rows to same ng-model name.

Do we need to maintain unique ng-model names for each row column?

Jonny C
  • 1,943
  • 3
  • 20
  • 36
janasainik
  • 811
  • 5
  • 20
  • 40
  • 1
    Please read [this question / answer](http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background) first. You will save yourself a lot of headache in the future – New Dev May 09 '15 at 19:26
  • This question has a great answer: http://stackoverflow.com/questions/21427089/how-to-add-dynamic-row-to-a-table-using-angularjs – jme11 May 09 '15 at 19:48

1 Answers1

2

You need to use the $compiler service or.. ngRepeat which is what i would use if I were you.

<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({});
    };
});
New Dev
  • 48,427
  • 12
  • 87
  • 129
bluetoft
  • 5,373
  • 2
  • 23
  • 26