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?

2

1 Answer 1

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({});
    };
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I should use ng-repeat to get array of all rows! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.