AngularJS and ng-grid - auto save data to the server after a cell was changed

Fabien picture Fabien · Mar 26, 2013 · Viewed 36.7k times · Source

My Use Case is pretty simple. A User, after editing a Cell (enableCellEdit: true), should have the data "automatically" sent to the server (on cell blur). I tried different approaches but none of them have properly worked out. I have a minimalistic grid:

// Configure ng-grid
$scope.gridOptions = {
    data: 'questions',
    enableCellSelection: true,
    selectedItems: $scope.selectedRow,
    multiSelect: false,
    columnDefs: [
        {field: 'id', displayName: 'Id'},
        {field: 'name', displayName: 'Name'},
        {field: 'answers[1].valuePercent', displayName: 'Rural', enableCellEdit: true}
    ]
};

For example, I tried to watch the data model passed to the Grid. But doing so won't return me the edited cell:

$scope.$watch('myData', function (foo) {
    // myModel.$update()
}, true);

I tried to fiddle with the "ngGridEventData" data event but it does not fire after cell edit

$scope.$on('ngGridEventData', function (e, gridId) {
    // myModel.$update()
});

Finally, I tried to observer a Cell. However, this only work for a row by the mean of the "selectedCell" property of the grid:

$scope.selectedRow = [];

$scope.gridOptions = {
    selectedItems: $scope.selectedRow,
}

$scope.$watch('selectedRow', function (foo) {
    console.log(foo)
}, true);

Is it a ng-grid plugin needed? I can't believe it is not something out of the box.

Would you have a pointer / snippet how I could solve the auto save / send to the server?

Answer

chriswhitmore picture chriswhitmore · Mar 2, 2014

Maybe this is new but ng-grid actually publishes events which can be used to implement a simple update on change.

Event Reference: https://github.com/angular-ui/ng-grid/wiki/Grid-Events

Example code (add to controller where you setup the grid):

$scope.$on('ngGridEventEndCellEdit', function(evt){
    console.log(evt.targetScope.row.entity);  // the underlying data bound to the row
    // Detect changes and send entity to server 
});

One thing to note is that the event will trigger even if no changes have been made, so you may still want to check for changes before sending to the server (for example via 'ngGridEventStartCellEdit')