Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/15647981/angularjs-and-ng-grid-auto-save-data-to-the-server-after-a-cell-was-changed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...