Matt W Matt W - 9 months ago 45
Javascript Question

Is it possible to cause UI-Grid's afterCellEdit to fire artificially?

I have this code in an app I inheritted:

onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
$scope.gridApi.edit.on.afterCellEdit($scope,
function(rowEntity, colDef, newValue, oldValue) {
}
}


I have updated the gridOptions object which is binding data to the UI Grid and so I would like the
afterCellEdit
callback to fire for the cell which renders the updated data.

Is this possible?

Answer Source

In answer to your question, this is how you'd cause UI-Grid's afterCellEdit to fire artificially when ANY grid data is updated outside the grid...

var app = angular.module('app', ['ui.grid', 'ui.grid.edit', 'ui.grid.cellNav']);
app.controller('MainCtrl', ['$scope', '$timeout', function($scope, $timeout) {
  $scope.gridData = [{"FirstName": "Matt", "LastName": "W", "Job": "Stack Overflow User"},
                     {"FirstName": "Tim", "LastName": "Harker", "Job": "Stack Overflow User"}];
  $scope.$watch('gridData', function(newValues, oldValues) {
    for (var i = 0; i < newValues.length; i++) {
      if (!angular.equals(newValues[i], oldValues[i])) {
        for (var property in oldValues[i]) {
          if (oldValues[i].hasOwnProperty(property)) {
            if (oldValues[i][property] != newValues[i][property]) {
              $scope.gridApi.edit.raise.afterCellEdit(newValues[i], null, newValues[i][property], $scope.gridOptions.data[i][property]);
            }
          }
        }
      }
    }
    $timeout(function() {
      $scope.gridOptions.data = angular.copy($scope.gridData);
    });
  }, true);
  $scope.callbackData = {};
  $scope.gridOptions = {
    enableCellEditOnFocus: true,
    onRegisterApi: function(gridApi) {
      $scope.gridApi = gridApi;
      $scope.gridApi.edit.on.afterCellEdit($scope,
        function(rowEntity, colDef, newValue, oldValue) {
          $scope.callbackData.oldValue = oldValue;
          $scope.callbackData.newValue = newValue;
        });
    },
    columnDefs: [{name: 'FirstName'}, {name: 'LastName'}, {name: 'Job'}]
  };
}]);
button {
  margin-bottom: 10px;
}

div[ui-grid] {
  height: 115px;
  margin-bottom: 10px;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.2/ui-grid.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.2/ui-grid.min.css" />
<div ng-app="app" ng-controller="MainCtrl">
  <button ng-click="gridData[0].LastName='Williams'">Guess Last Name</button>
  <div ui-grid="gridOptions" ui-grid-edit ui-grid-cellNav></div>
  <div>{{callbackData}}</div>
</div>

Let me know if you have any further questions.