Stephanie Cray Stephanie Cray - 2 years ago 185
AngularJS Question

How to access gridApi in UI-grid with using $scope?

The app I am working on requires me to access the paginationChanged function which is only available to me if I were to add an onRegisterApi object to my gridOptions in the table. I need to access the paginationChanged function so that I can change the height of the grid as the PageSize increases. The only way that I know of to access the the gridApi is to inject $scope which is no longer being used in since Angular 1.6 and up. Right now I am using Angular 1.6 and to access the gridOptions on the html view is through the use of ui-grid= $ctrl.gridOptions. Does anyone know of a way to access the gridApi when part of the onRegisterApi object without having to use $scope?

Answer Source

The way to access gridApi without the usage of $scope in the controller or service where your gridOptions object lives is to make sure that you add the following properties: appScopeProvider: which allows you to set the name of your this object which is my case was $ctrl. and onRegisterApi: which is needed to allow you to access to the gridApi. Reference http://ui-grid.info/docs/#/api/ui.grid.class:GridOptions

When you use appScopeProvider to reset the name of your this object , you also are setting the name for the gridApi. So in instead of using the $ctrl.gridapi you would only need to use $ctrl by itself. So in my case the solution was the following:

 var OverViewTable = function ($ctrl) {
     var gridOptions = {
         enableSorting: true,
         enablePagination: true,
         enablePaginationControls: true,
         paginationPageSizes: [50, 100, 200],
         paginationPageSize: 50,
         rowHeight: 60,
         appScopeProvider:$ctrl,
         onRegisterApi: function ($ctrl){
         $ctrl.pagination.on.paginationChanged(null, function(newPage, 
          pageSize){}

I also had to set where you would normally see $scope to null as an argument in the function paginationChanged() since I didn't want to use $scope.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download