Choose a row in an Angular ngGrid upon loading the page

My question is in relation to this inquiry

How can I retrieve selected rows from ng-grid?

Check out the plunker sample - http://plnkr.co/edit/DiDitL?p=preview

Upon page load, I am looking to have a row pre-selected without relying on 'ngGridEventData'

Attempting to call $scope.gridOptions.selectRow(2, true); in the controller fails as the grid has not been loaded yet.

I would like to avoid listening to ngGridEventData because I need the controller to respond to a preceding event and select the nggrid row based on that.

Any suggestions or insights to solve this issue?

Answer №1

Make sure to include the $timeout in your Controller and implement the following code:

$timeout(function() { 
    $scope.gridOptions.selectRow(2, true); 
});

Take a look at this example: http://plnkr.co/edit/hDv7b8?p=preview

Answer №2

For a solution that does not have a timeout, you can visit the following links: Solution on Github and also check out: Pre-select rows on load using angular-ui-grid

$scope.gridOptions = {
...
                onRegisterApi : function (gridApi) {
                    $scope.gridApi = gridApi;
                    $scope.gridApi.grid.modifyRows($scope.gridOptions.data);
                    $scope.gridApi.selection.selectRow($scope.gridOptions.data[0]);
                }
            };

It seems that modifyRows feature requires version v3.0.0-rc.22 or later.

Answer №3

None of the solutions provided worked for me (using ng-grid v2.0.14).

The solution mentioned might work when the data is not extensive or not fetched via an ajax call. Selecting a row "before" ngGridEventData is not feasible because this event is triggered after the rows are rendered. Therefore, if the conditions mentioned are not met or if there is a delay in rendering the grid, the suggested solution may fail.

In my case, I have a grid with around 2000 scrollable rows, and I do not restrict listening to ngGridEventData. I observed that this event is fired four times for me - twice before the data is retrieved from the ajax call and twice after. To handle this behavior, I utilized the jQuery plugin available at to ensure that the function is only called once.

Additionally, the "selectRow/selectItem" function triggers the "afterSelectionChange" event twice, with the first trigger selecting the wrong row for unknown reasons. To address this, I implemented measures to ensure that the event is fired only once and for the correct row.

Here is the sequence of events I experienced:

  • ngGridEventData (no afterSelectionChange triggers, likely due to no rendered rows)
  • ngGridEventData (no afterSelectionChange triggers, likely due to no rendered rows)
  • Ajax call to fetch data
  • Delay (possibly for rendering)
  • ngGridEventData
  • afterSelectionChange x2
  • ngGridEventData
  • afterSelectionChange x2

To address these issues, I implemented the following:

  • Utilized debounce to ensure the function is only called once during the delay, considering the proximity of the calls and checking for rendered rows
  • Checked that rendered rows are greater than 0 to avoid triggers on slow systems or connections causing delays in rendering and data loading
  • Optionally used rowItem.selected to mitigate issues with afterSelectionChange firing twice, even for row selections
  • Implemented the fireOnlyOnce variable to prevent double calling of the afterSelectionChange function

Sample code snippet:

$scope.fireOnlyOnce=true;
$scope.gridOptions = {
    //Grid Options Here
    afterSelectionChange: function (rowItem) {
        if($scope.fireOnlyOnce){
            if(rowItem.selected){
                //Perform actions
            }
        } else {
            $scope.fireOnlyOnce=true;
        }
    }
};

$scope.$on('ngGridEventData', jQuery.debounce(100, function (row, event){   
    var renderedRows = row['targetScope'].renderedRows.length;
    if(renderedRows>0){
        $scope.fireOnlyOnce=false;
        $timeout(function(){$scope.gridOptions.selectRow(2, true)});
    }
}));

Answer №4

Although the answer was given a while back, I still believe there is a code smell present (no disrespect to the original poster, but it does appear sub-optimal).

My approach involved utilizing the ngGridEventData event within the grid.

It is important to exercise caution as this event can trigger multiple times (once for each row added). However, by leveraging our knowledge of the data size and the event's capability to track rendered rows, we can determine when the last row is displayed. This indicates that the grid is not yet fully rendered. (Note: I have not tested this scenario with scrolling grids, where certain rows may not be visible. Can someone verify if this method works in such cases? Personally, I avoid using scrolling grids as I find them more suited for desktop applications rather than browser pages).

Here is a snippet of the code:


$scope.$on('ngGridEventData', function (row, event) 
{
if (event == $scope.vehicleTypeGridOptions.gridId)
{
console.info('@+@ vehicleTypeGridOptions grid updated');
var renderedRows = row['targetScope'].renderedRows.length;
console.info('renderedRows = ' + renderedRows + '; num data rows = ' + $scope.vehicleTypesGridData.length); 

if (renderedRows == 0)
{
return;
}

// if grid rowcount = data length, it is fully displayed
if (renderedRows == $scope.vehicleTypesGridData.length) 
{
console.log('vehicleTypeGrid fully rendered. Select row zero, then populate vehicleDescriptionGrid');
console.info('Select row zero');
$scope.vehicleTypeGridOptions.selectItem(0, true); // Grid rendered, select first row
// console.table($scope.vehicleTypeGridOptions.selectedItems);
var vehicle_type = $scope.vehicleTypeGridOptions.selectedItems[0].vehicle_type;
console.info(vehicle_type);
}
}

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

The act of splicing an array in React causes continuous rerendering

Within the update(changeProps) function, my code resembles the following: update(changedProps) { if (this.person) { this.__arr = ['hi', 'hi', 'hi']; } else { this.__arr = ['bye', &apos ...

Explore button that gradually decreases max-height

I have a "Show More" button that expands a div by removing the css attribute max-height, but I want to add an animation similar to jQuery's slideToggle() function to smoothly reveal the rest of the content. This is the code I am using: <div id="P ...

Is there a way to disregard the data returned from previous AJAX calls?

I've been wondering about a strategy for managing delayed AJAX data returns in a scenario where newer calls should take precedence over earlier ones. For instance, if a first data fetch initiated at 12:01:33 is delayed and comes back at 12:01;39, whil ...

The issue at hand is the malfunctioning of Angular form submission within an ng-repeat loop

Whenever I submit a form within an ng repeat loop, the form value does not get passed. <li ng-repeat="com in post.comments">{{ com.body }} <h4>Reply</h4> <form ng-submit="addReply()"> <textarea n ...

The Next.js component only appears after a page reload

Essentially, I have a nested component that is supposed to render with the parent component and it works fine when the server initially starts. However, the issue arises when switching back from another page – some of the nested components disappear. A ...

javascript image alert

I want to upgrade a basic javascript alert to make it look more visually appealing. Currently, the alert is generated using if(isset($_GET['return'])) { // get a random item $sql = "SELECT * FROM pp_undergroundItems AS u LEFT JO ...

Exploring JSON data with multiple nested layers of iteration

I'm currently working on a project that involves parsing through a JSON file with a complex structure. I've been attempting to extract a link to an image within the JSON data, but my current approach is resulting in an error. Below you'll fi ...

Email address string loses the '+"' when using AJAX

My ajax code has been working well in most cases, but when I tried using it for updating user details on my page, I noticed that the ""+"" symbol was getting lost if used in an email address (such as <a href="/cdn-cgi/l/email-protection" class ...

The jsonp typeahead feature is not populating the uib-typeahead form element

Trying to populate a uib-typeahead from the ui-bootstrap modules using a jsonp callback function in a factory method has been challenging. This is the factory function being used: autoCompleteCity: function(city){ return $http.jsonp("http://g ...

Creating a captivating animation for a social media like button with CSS

I came across some animation code on the web and noticed that when I click the image, it replays the animation from the starting point. I want to make it so that when I click the image, the animation plays and stops, and if clicked again, resets the image. ...

The use of a <button> element in a React App within a Web Component with Shadow DOM in Chrome disables the ability to highlight text

An unusual problem has arisen, but I have a concise example that demonstrates the issue: https://codesandbox.io/s/falling-architecture-hvrsd?file=/src/index.js https://i.stack.imgur.com/CkL4g.png https://i.stack.imgur.com/nDjuD.png By utilizing the divs ...

How can I duplicate an element twice in AngularJS, without having them appear right after each other?

Within my AngularJS template html file, I am faced with a dilemma regarding an html element: <div>This is a complex element that I want to avoid typing multiple times</div> My challenge is that I need this element to show up twice on my websi ...

When I place this in the js directory, the function does not seem to function properly

I have an add.ctp file where I can add multiple rows. However, when I place the addNumber function in app/webroot/js, it does not work. Why is that? Here is a snippet from my view file (add.ctp): <table id="mytable"> <tr id="number0" sty ...

Trouble with npm installation on Windows following node update

After updating my Node.JS last night, my npm install function stopped working. I tried uninstalling and reinstalling Node, but it didn't solve the issue. My system is running on Windows 8.1 with Node version 8.9.4 and NPM version 3.3.12. The error mes ...

Utilizing JSON API filtering within a Next.js application

Recently delving into the world of coding, I've embarked on a personal project that has presented me with a bit of a challenge regarding API filtering. My goal is to render data only if it contains a specific word, like "known_for_department==Directin ...

Ways to implement debounce in handling onChange events for input fields in React

I've been attempting to implement debounce functionality in my React app without relying on external libraries like lodash or third-party node modules. I've tried various solutions found online, but none have worked for me. Essentially, in the h ...

Is it possible to incorporate custom meta tags into next.js 13 using static metadata objects?

I'm trying to block Pinterest on my website by adding the meta tag <meta name="pinterest" content="nopin" /> in the site's header, but I'm uncertain how to do this in Next 13 using the new exported metadata object f ...

Unexpected outcome when converting a while loop to a .forEach statement

Exploring a practical demonstration of sorting an array of objects based on multiple properties, the code implementation involves a while loop (refer to students1 in the snippet below). I attempted to streamline this process by using .forEach, but encounte ...

Notification does not appear once the full content of all iframes on the page has been loaded

<!DOCTYPE html> <html lang="en"> <head> <title> </title> <meta charset="utf-8" /> <link rel="stylesheet" type="text/css" href="css/custom.css" /> </head> <bo ...

How to adjust the "skipNatural" boolean in AngularJS Smart-Table without altering the smart-table.js script

Looking to customize the "skipNatural" boolean in the smart-table.js file, but concerned about it being overwritten when using Bower for updates. The current setting in the Smart-Table file is as follows: ng.module('smart-table') .constant(&ap ...