All about UI-Grid: Mastering the process of selecting records on the current page with the convenient selectAll checkbox option

In the UI-grid, there is a "select All" checkbox that, when checked, selects all the records visible on the current page and other pages.

Query - Is there a way to select rows displayed only on the current page?

You can check out the example on plunker: http://plnkr.co/edit/gHiER0A2Oaia4HMWChcG?p=preview

I have tried using the API

$scope.gridApi.selection.selectAllVisibleRows();
but it seems to select rows across all pages. Even if you click on "Select Visible Rows" and move to the next page, the records there are also selected.

Additional information about the API selectAllVisibleRows

Upon checking inside the ui-grid function selectAllVisibleRows, the row.visible returns true for all the rows across all pages.


selectAllVisibleRows: function (evt) {
    if (grid.options.multiSelect === false) {
        return;
     }

    var changedRows = [];
        grid.rows.forEach(function (row) {
        if (row.visible) {
           if (!row.isSelected && row.enableSelection !== false){
              row.setSelected(true);
              service.decideRaiseSelectionEvent( grid, row, changedRows, evt );
           }
        } else {
          if (row.isSelected){
             row.setSelected(false);
             service.decideRaiseSelectionEvent( grid, row, changedRows, evt );
          }
        }});
    service.decideRaiseSelectionBatchEvent( grid, changedRows, evt );
    grid.selection.selectAll = true;
},

Answer №1

Experiment with the for loop method! You can find a helpful plunker link here.

Answer №2

In order to exclusively select the rows on the current grid page, it is necessary to implement a handler for the ui-grid event rowSelectionChangedBatch when registering the API method. While considering only unfiltered rows as visible, this approach does not account for rows that are not rendered on the current grid page. Therefore, a manual intervention becomes essential:

        onRegisterApi: function (gridApi) {

            gridApi.selection.on.rowSelectionChangedBatch(null, function (rows) {
                var grid = this.grid;
                // Requires ui-grid v4.4.9 or newer 
                // Alternatively, an adjustment is needed in getSelectAllState() if using an older version
                // Details can be found at https://github.com/angular-ui/ui-grid/issues/5411
                var isAllSelected = grid.api.selection.getSelectAllState();
                // When 'select all' is enabled, all grid rows across all pages are selected by default
                // Hence, we must deselect them first before selecting just those on the current page
                grid.api.selection.clearSelectedRows(null);
                if (isAllSelected) {
                    // Only select the rows displayed in the current grid view
                    var startIndex = (grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize;
                    var endIndex = startIndex + grid.options.paginationPageSize;
                    for (let i = startIndex; i < endIndex; i++) {
                        let row = grid.rows[i];
                        row.isSelected = true;
                    }
                }
            });
        },

Answer №3

registerSelectionFunction: function(api) {
    api.selection.on.rowBatchSelectionChange($scope, function() {

        // check the ui-grid version to determine whether to change the selection
        var allSelected = api.selection.getSelectAllState();

        if (allSelected) { 

            // deselecting all rows as the select all button usually selects all rows
            api.selection.clearSelectedRows();

            /* Fetching only the grid rows that are visible on the current page,
               regardless of any sorting, pagination, or filters applied */
            var visibleGridRows = this.grid.getVisibleRows();


            // setting selected status for only the visible rows
            angular.forEach(visibleGridRows, function(row) { 
                row.setSelected(true);
            });
        }
        $scope.selectedRows = api.selection.getSelectedRows();
   });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the error when attempting to retrieve an index using the window variable?

I'm facing a strange issue where I am trying to utilize a variable that I define as follows: window.params['variable'] = { ... }; Within the function that I am using, the code looks like this: function q() { ... // for example return n ...

Passing objects to an AngularJS form using UIB TypeAhead without two-way binding

In my current situation, I am encountering an issue with a typeahead feature on a repeating form element that consists of 5 input fields. While everything functions correctly when selecting results and populating the input fields, the model does not get up ...

AngularJS utilizes deferred.resolve() to provide functionality for handling asynchronous operations and

Is there a way to intercept the ng-view change and display a "loading div" overlay until all new images are loaded? I've been attempting to suspend promise callbacks in my HttpInterceptor, but I'm struggling to resolve my promise for a second ti ...

What could be the reason for parent props not updating in child components in VueJS?

Hello, I am new to VueJS and encountering an issue. In the main.js file, I am passing the user variable to App.vue using props. Initially, its value is {} The getLoginStatus() method in main.js monitors the firebase authentication status, and when a user ...

Tips for maintaining the reference of a Three.js object after importing it as an .obj file

If you want to learn how to incorporate a .obj file into your scene, the official documentation provides a helpful example that can be found here. const loader = new OBJLoader(); // Load the resource loader.load( // Resource URL 'models/monst ...

Utilize the toggle feature by retrieving the dynamic ID from ng-repeat within the scope

Hey there! I'm currently working on a UI that contains multiple links, and when clicked, each link should toggle to display different data. The challenge I'm facing is that the data is being generated dynamically using ng-repeat. How can I ensure ...

Vanilla Javascript's alternative to $(document).on

Can someone provide me with the plain vanilla JavaScript code equivalent to the jQuery code below? $(document).on("mousemove touchmove", function(e) { console.log(e.touches[0].pageX); //code }); I understand how to implement this in ...

How can you identify if JavaScript is turned off without relying on the noscript tag?

While working on designing a pop-up notification for cases when JavaScript is disabled, I incorporated html, css, and bootstrap elements into my project. An issue arose as I pondered if there exists a method to identify whether the html class within my p ...

jQuery Swiper slider

I am currently working with the Swiper jQuery slider for my project. As a beginner in programming (js / jquery), I am looking to run a specific function, involving some jquery code, whenever the first slide of the slider is active. It seems that this can ...

Steps to invoking an asynchronous function within another async function

Is there a way for me to transform the following function into an Async function? I need to invoke several methods based on the result of the function call when isMaxAttemptExceeded has been fully executed. let isMaxAttemptExceeded = async () =&g ...

Which is the better option for data storage: JSON files or MySQL database?

I am currently developing a project that utilizes the vis.js JavaScript framework to showcase a visual network of various categories. There are approximately 2000 categories available for selection, each with a substantial amount of associated data. I am ...

Combine API calls using promises

The functionality of a plugin I'm using is currently not functioning as expected, leading me to merge two separate requests. Below is the code I am utilizing: Although I am able to receive a response, I am facing difficulties in checking for response ...

Determine the frequency of each element in an array and arrange them in ascending order

In my quest to locate occurrences of numbers within an array, I aimed to display the numbers and their respective frequencies in ascending order. Here is what I was trying to achieve: let arr = [9,-10,2,9,6,1,2,10,-8,-10,2,9,6,1]; // {'-10': 2, ...

Switching classes in jQuery for Internet Explorer 8

I am attempting to update the color of a header when it reaches a certain scroll position. I have implemented this script using jQuery: var $document = jQuery(document), $element = jQuery('#header'), className = 'red'; $docume ...

The process of how React attaches event listeners to elements created through the map method

Upon clicking discountKeyboard, an error was encountered: Alert: Functions cannot be used as a React child. This issue may arise if you return a Component instead of from render. Alternatively, it could be due to calling the function rather than returnin ...

Modify Bootstrap Card Styling Using JavaScript

When the clock strikes certain evening hours on my website, the Bootstrap card's default light style no longer fits the dark theme. I've attempted to switch the card to a dark style by tying in some JavaScript code, but it's not quite doing ...

creating a personalized dropdown menu with react javascript

Is it possible to create a chip in a single select dropdown in React? In a multi-select dropdown, a chip is created as shown in the example below. Can we achieve the same effect in a single selection dropdown? const DropdownExampleClearableMultiple = () = ...

How can I apply a texture to a 3D rectangle in THREE.js?

I am attempting to create a 3D box in THREE.js that represents a box made up of 2x4 Legos, measuring 24 pieces wide by 48 pieces long and an unspecified number of pieces tall. I have created a texture displaying this pattern using random colors: https://i ...

Remove any JSON objects in JavaScript or AngularJS that match another JSON object

JSON A ['711','722','733','744'] JSON B [{pid: 711, name: 'hello'},{pid: 733, name: 'world'}, {pid: 713, name: 'hello'},{pid: 744, name: 'hellosdaf'}] I am attempting to remo ...

What is the best way to modify a particular h4 tag without impacting the rest?

Hey everyone, I'm re-uploading this post because I realized my previous explanation was unclear. I apologize for that and have deleted the old post. I am seeking to make some edits: <div id="viewer_viewer_container" style="display: block;"> ...