Вопрос

I'm trying to make use of ngGrid. The list represents a bunch of items which the users then can select (or not). This selection should be persisted so when the user comes back the grid shows the same selected items as last time. I made a plunker

However I've run into a bit of a problem using ngGrid.

I'm using afterSelectionChange to save selection changes to the grid.

$scope.gridOptions = { 
  data: 'myData',
  showSelectionCheckbox: true,
  afterSelectionChange: function(rowItem, event) {
    // $http... save selection state
  }
};

Which is fine. However when I want to select rows programmatically when the page loads all hell breaks loose. The below code is supposed to select the row with the name Enos, and it does. But it triggers afterSelectionChange 4 times.

$scope.$on('ngGridEventData', function() {
    angular.forEach($scope.myData, function(data, index) {
        if (data.name == 'Enos') {
            $scope.gridOptions.selectItem(index, true);
        }
    });
});

That can't be intended. I made a plunker.

How to persist selected rows using ngGrid?

Это было полезно?

Решение

Don't know why this is firing 4 Times, but it does not happen when you use selectedItems:

$scope.gridOptions = { 
  data: 'myData',
  showSelectionCheckbox: true,
  selectedItems:$scope.output
};

Not really an answer, but maybe it helps you.

Forked Plunker

Update Found out some more:

The event ngGridEventData is fired 2 times:

  1. On Initialization AND after selectItem by a watcher.

  2. Also afterSelectionChange is fired 2 time. The rowItem from first call is a clone (from cache?) the second one is noClone.

This sums up to 4!

So by taking init out of ngGridEventdata and replacing it with a timeout as well as only pushing rowitems when they are a clone (why?) resolves this issue.

    $scope.gridOptions = {
    data: 'myData',
    showSelectionCheckbox: true,
    afterSelectionChange: function(rowItem, event) {
      if (rowItem.isClone) {
        $scope.output.push({
          name: rowItem.entity.name,
          selected: rowItem.selected
        });
        $scope.num++;
      }
    }
    };
    setTimeout(function() {
    angular.forEach($scope.myData, function(data, index) {
      if (data.name == 'Enos') {
        $scope.gridOptions.selectItem(index, true);
      }
    });
    })

I know this is still not an answer and smells like a bug to me, but here is another forked Plunker anyhow.

Of course you now have to find a way how to splice items out of the array when they are unselected. Good Luck!

Другие советы

I figured it out - or sort of.

Using beforeSelectionChange instead of afterSelectionChange I get the expected behavior. The documentation is lagging some information.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top