Search code examples
angularjsngtable

how to add a row to ngTable


I am trying to add data from a typeahead selection to rows in a ngTable. I was using a regular bootstrap table for this but I needed to be able to edit the data after the row was added. INgTable has a table that can do this so I wanted to switch. I am not familiar with ngTable so any help would be great. plunkr

   //Add New POD Row
$scope.data = [];
$scope.addRow = function () {
    $scope.data.push({
        'JobItemName': $scope.masterItem.MLItemCode,
        'JobItemDescription': $scope.masterItem.JobItemDescription,
    });
    $scope.masterItem.JobItemName = '';
    $scope.masterItem.JobItemDescription = '';
};
//Remove POD Row
$scope.removeRow = function (JobItemName) {
    var index = -1;
    var comArr = eval($scope.data);
    for (var i = 0; i < comArr.length; i++) {
        if (comArr[i].JobItemName === JobItemName) {
            index = i;
            break;
        }
    }
    if (index === -1) {
        alert("Something gone wrong");
    }
    $scope.data.splice(index, 1);
};

   $scope.tableParams = new ngTableParams({
            page: 1,            // show first page
            count: 10           // count per page
        }, {
            total: $scope.data.length, // length of data
            getData: function($defer, params) {
                $defer.resolve($scope.data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
            }
        });

Solution

  • Why use the ngTable directive and not something like this :

    <table class="table table-striped table-hover">
            <thead>
            <tr>
                <th>Column 1</th>
                <th>Column 2</th>
            </tr>
            </thead>
            <tbody>
            <tr ng-repeat="row in table" ng-click="editMyRow(row)">
                <td ng-bind="row.column1"></td>
                <td ng-bind="row.column2"></td>
            </tr>
            </tbody>
        </table>
    

    In this case, everytime you edit those values, your table will change in real time.

    The controller would be something like :

    angular.module('test').controller('blah', $scope){
    
     $scope.table = {};
     $scope.table.row = [];
     $scope.table.row.add({
          column1: '',
          column2: ''
     });
    
    }