javascript - AngularJS + ag-grid : sticky/remembered selections with virtual paging/infinite scrolling

标签 javascript angularjs datagrid angular-ui-router ag-grid

在 AngularJS 应用程序中,我有一个 ag-grid使用 virtual paging/infinite scrolling从太大而无法立即显示的数据集中延迟加载行。我已开启check-box selection在第一列中,以便用户应该能够为任意特定于应用程序的操作选择单独的行。

AngularJS 应用程序使用 ui-router控制多个 View 。因此,以 virtual-paging example with "sorting & filtering" 为基础,包含有关奥运会获奖者的构建数据,来自 ag-grid文档,我进一步扩展了代码。来自 index.html :

<body ng-controller="MainController" class="container">
  <div ui-view="contents"></div>
</body>

以及以下ui-router状态:

myapp.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise("example.page1")

  $stateProvider
    .state('example', {
      abstract: true,
      views: {
        contents: {
          template: '<div ui-view="example"></div>'
        }
      }
    })
    .state('example.page1', {
      url: '/page1',
      views: {
        example: {
          templateUrl: 'page1.html'
        }
      }
    })
    .state('example.page2', {
      url: '/page2',
      views: {
        example: {
          template: 'Go back to the <a ui-sref="example.page1">example grid</a>.'
        }
      }
    });
});

哪里page1.html看起来像下面这样:

<div ng-controller="GridController">
  <div ag-grid="gridOptions" class="ag-fresh" style="height: 250px;"></div>
</div>
<div>
  <h3>Selected rows:</h3>
  <ul class="list-inline">
    <li ng-repeat="row in currentSelection track by row.id">
      <a ng-click="remove(row)">
        <div class="badge">#{{ row.id }}, {{ row.athlete }}</div>
      </a>
    </li>
  </ul>
</div>
<p>Go to <a ui-sref="example.page2">the other page</a>.</p>

我想要实现的目标:

  1. ag-grid 中所做的选择当将(虚拟)页面滚动到 View 之外并再次返回时,会记住(粘性),以便用户可以在不同页面上选择多行。
  2. 记住的选择在网格外部可用,并且支持添加和删除选择(如 ng-click="remove(row)" 中的 page1.html 的预期,如上所示)。
  3. 当使用 ag-grid 从 View 切换时,应记住这些选择。到另一个,然后再返回。
  4. (可选)记住用户 session 中的选择。

我怎样才能做到这一点?

最佳答案

我创建了一个 working example这个可以实现。

首先,我们将编写一个 AngularJS 服务 selectionService 来跟踪选择:

function _emptyArray(array) {
  while (array.length) {
    array.pop();
  }
}

function _updateSharedArray(target, source) {
  _emptyArray(target);
  _.each(source, function _addActivity(activity) {
    target.push(activity);
  });
}

myapp.factory('selectionService', function ($rootScope, $window) {
  var _collections = {},
    _storage = $window.sessionStorage,
    _prefix = 'selectionService';

  angular.element($window).on('storage', _updateOnStorageChange);

  function _persistCollection(collection, data) {
    _storage.setItem(_prefix + ':' + collection, angular.toJson(data));
  }

  function _loadCollection(collection) {
    var item = _storage.getItem(_prefix + ':' + collection);
    return item !== null ? angular.fromJson(item) : item;
  }

  function _updateOnStorageChange(event) {
    var item = event.originalEvent.newValue;
    var keyParts = event.originalEvent.key.split(':');

    if (keyParts.length < 2 || keyParts[0] !== _prefix) {
      return;
    }
    var collection = keyParts[1];
    _updateSharedArray(_getCollection(collection), angular.fromJson(item));
    _broadcastUpdate(collection);
  }

  function _broadcastUpdate(collection) {
    $rootScope.$emit(_service.getUpdatedSignal(collection));
  }

  function _afterUpdate(collection, selected) {
    _persistCollection(collection, selected);
    _broadcastUpdate(collection);
  }

  function _getCollection(collection) {
    if (!_.has(_collections, collection)) {
      var data = _loadCollection(collection);
      // Holds reference to a shared array.  Only mutate, don't replace it.
      _collections[collection] = data !== null ? data : [];
    }

    return _collections[collection];
  }

  function _add(item, path, collection) {
    // Add `item` to `collection` where item will be identified by `path`.
    // For example, path could be 'id', 'row_id', 'data.athlete_id',
    // whatever fits the row data being added.
    var selected = _getCollection(collection);

    if (!_.any(selected, path, _.get(item, path))) {
      selected.push(item);
    }

    _afterUpdate(collection, selected);
  }

  function _remove(item, path, collection) {
    // Remove `item` from `collection`, where item is identified by `path`,
    // just like in _add().
    var selected = _getCollection(collection);

    _.remove(selected, path, _.get(item, path));

    _afterUpdate(collection, selected);
  }

  function _getUpdatedSignal(collection) {
    return 'selectionService:updated:' + collection;
  }

  function _updateInGridSelections(gridApi, path, collection) {
    var selectedInGrid = gridApi.getSelectedNodes(),
      currentlySelected = _getCollection(collection),
      gridPath = 'data.' + path;

    _.each(selectedInGrid, function (node) {
      if (!_.any(currentlySelected, path, _.get(node, gridPath))) {
        // The following suppressEvents=true flag is ignored for now, but a
        // fixing pull request is waiting at ag-grid GitHub.
        gridApi.deselectNode(node, true);
      }
    });

    var selectedIdsInGrid = _.pluck(selectedInGrid, gridPath),
      currentlySelectedIds = _.pluck(currentlySelected, path),
      missingIdsInGrid = _.difference(currentlySelectedIds, selectedIdsInGrid);

    if (missingIdsInGrid.length > 0) {
      // We're trying to avoid the following loop, since it seems horrible to
      // have to loop through all the nodes only to select some.  I wish there
      // was a way to select nodes/rows based on an id.
      var i;

      gridApi.forEachNode(function (node) {
        i = _.indexOf(missingIdsInGrid, _.get(node, gridPath));
        if (i >= 0) {
          // multi=true, suppressEvents=true:
          gridApi.selectNode(node, true, true);

          missingIdsInGrid.splice(i, 1);  // Reduce haystack.
          if (!missingIdsInGrid.length) {
            // I'd love for `forEachNode` to support breaking the loop here.
          }
        }
      });
    }
  }

  var _service = {
    getCollection: _getCollection,
    add: _add,
    remove: _remove,
    getUpdatedSignal: _getUpdatedSignal,
    updateInGridSelections: _updateInGridSelections
  };

  return _service;
});

selectionService 服务允许向单独的集合中添加和删除任意对象,这些对象由 collection(您认为合适的名称)标识。这样,可以使用相同的服务来记住多个ag-grid实例中的选择。每个对象都将使用 path 参数进行标识。 path 用于使用 lodash's get 检索唯一标识符。功能。

此外,该服务使用 sessionStorage在用户的整个选项卡/浏览器 session 期间保留选择。这可能有点矫枉过正了;我们可以依靠该服务来跟踪选择,因为它只会实例化一次。当然可以根据您的需要进行修改。

然后必须对 GridController 进行更改。首先,第一列的 columnDefs 条目必须稍微更改

  var columnDefs = [
    {
      headerName: "#",
      width: 60,
      field: 'id',  // <-- Now we use a generated row ID.
      checkboxSelection: true,
      suppressSorting: true,
      suppressMenu: true
    }, …

从远程服务器检索数据后,将生成新的行 ID

       // Add row ids.
       for (var i = 0; i < allOfTheData.length; i++) {
         var item = allOfTheData[i];

         item.id = 'm' + i;
       }

(包含 ID 中的 'm' 只是为了确保我不会将该 ID 与 ag-grid 使用的其他 ID 混淆。)

接下来,对 gridOptions 进行必要的更改,添加

{
  …,
  onRowSelected: rowSelected,
  onRowDeselected: rowDeselected,
  onBeforeFilterChanged: clearSelections,
  onBeforeSortChanged: clearSelections,
  …
}

不同的处理程序是否非常简单,与 selectionService 进行通信

  function rowSelected(event) {
    selectionService.add(event.node.data, 'id', 'page-1');
  }

  function rowDeselected(event) {
    selectionService.remove(event.node.data, 'id', 'page-1');
  }

  function clearSelections(event) {
    $scope.gridOptions.api.deselectAll();
  }

现在,GridController 也需要处理由 selectionService 发出的更新信号

  $scope.$on('$destroy',
             $rootScope.$on(selectionService.getUpdatedSignal('page-1'),
                            updateSelections));

  function updateSelections() {
    selectionService.updateInGridSelections($scope.gridOptions.api, 'id', 'page-1');
  }

调用selectionService.updateInGridSelections,这将更新相关网格的网格内选择。这是写起来最麻烦的函数。例如,如果已在外部(网格外)添加了选择,那么即使我们知道已在网格内选择了所有必要的节点,我们也必须执行 forEachNode 运行;没有办法提前退出该循环。

最后,另一个关键是当过滤器或排序顺序更改时,或者从服务器检索新数据时(仅在演示中模拟),分别清除并重新应用之前和之后的选择。解决方案是在 getRows 处理程序内的 params.successCallback 之后包含对 updateSelections 的调用

             params.successCallback(rowsThisPage, lastRow);
             updateSelections();

现在,在实现此解决方案期间最令人费解的发现是 ag-grid API 网格选项 onAfterFilterChangedonAfterSortChanged 无法“不能用于重新应用选择,因为它们在(远程)数据完成加载之前触发。

关于javascript - AngularJS + ag-grid : sticky/remembered selections with virtual paging/infinite scrolling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33777410/

相关文章:

javascript - 我如何收集类的 css 属性,只给出类名?

c# - 绑定(bind)到 WPF DataGrid 时使用数据虚拟化并支持排序

javascript - HREF 中的函数无法使用 javascript

javascript - ng-style 应用得太晚了

ruby-on-rails - 无法在 Ruby on rails 应用程序中加载模板 : template/typeahead/typeahead. html

angularjs - Azure管道 "npm install"但包不再存在

python - wxpython如何重新创建网格?

vb.net - 在vb.net中的datagridview中添加行号

javascript - JS Sequelize "Where Related"查询?

javascript - 谷歌浏览器上传速度与 Firefox