AngularJS and ng-grid - auto save data to the serv

2019-01-10 06:48发布

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?

7条回答
Melony?
2楼-- · 2019-01-10 07:42

I've found what I think is a much nicer solution:

  cellEditableTemplate = "<input ng-class=\"'colt' + col.index\" ng-input=\"COL_FIELD\" ng-model=\"COL_FIELD\" ng-change=\"updateEntity(row.entity)\"/>"

Using ng-change this way will cause updateEntity to be called with the entire object (row) that has been changed and you can post it back to the server. You don't need any new scope variables. A deficiency of the previous solution was that when you clicked in to start editing the field, it would always be blank instead of the original value before you began to edit.

That will cause updateEntity() to be called on each keystroke. If that is too frequent for you, you could use a timeout before posting to the server, or just use updateEntity() to record the id you want to push, and then use ng-blur to post the recorded id.

查看更多
登录 后发表回答