How can I make the clicking of a button in an ng-grid table delete a row from the model?

user1464139 picture user1464139 · Apr 11, 2013 · Viewed 15.4k times · Source

I have set up the following with ng-grid:

    var gridData = {};
    $scope.gridOptions = {
        data: 'gridData',
        enableCellEdit: true,
        multiSelect: false,
        columnDefs: [
            { field: 'testId', displayName: 'Test Id' },
            { field: 'name', displayName: 'Name', enableCellEdit: true, editableCellTemplate: cellEditableTemplate },
            { field: 'description', displayName: 'Description', enableCellEdit: true, editableCellTemplate: cellEditableTemplate },
            { field: '', cellTemplate: '<button ng-click="delete(row)">Delete</button>' }
        ]
    };

and:

   $scope.delete = function (row) {
      row.entity.$deleteData({ testId: row.entity.testId });
   }

This sends a HTTP message to the server which deletes the row. However the row still remains in the grid. How can I make it so the click of the delete button on a row also deletes a row from the gridData object?

Answer

jpmorin picture jpmorin · Apr 11, 2013

Like Valentyn Shybanov mentioned it in his comment, you should check if the server successfully deleted the object in the database, and then remove it from the gridData array.

$scope.delete = function(row) {
    row.entity.$deleteData({testId:row.entity.testId})
        .then(function(response) {
            if (response.status === 'OK') {
                remove($scope.gridData, 'testId', row.entity.testId);
            }
        });
}

// parse the gridData array to find the object with testId
function remove(array, property, value) {
    $.each(array, function(index, result) {
        if (result[property] == value) {
            array.splice(index, 1);
        }
    });    
});

The "Remove function" was taken from: https://stackoverflow.com/a/6310763/1036025