Implementing a loading spinner in Angular UI Grid

Can anyone please help me figure out how to display a basic loader while data is being loaded? I am currently using ng-grid-1.3.2 and have searched on Google for examples, but haven't found any yet. Any help would be greatly appreciated. Thanks!

Answer №1

As recommended by Maxim Shoustin, you can utilize the angularjs-spinner created by Jim Lavin, which utilizes the deprecated Response Interceptors.

The best explanation can be found here:

To implement this in your ng-grid app, you need to:

1) Insert the loading gif into your html (refer to this for loading gif options)

<div id="loadingWidget" class="row-fluid ui-corner-all" style="padding: 0 .7em;" loading-widget >
    <div class="loadingContent">
        <p>
            <img alt="Loading Content" src="images/ajax-loader.gif" /> Loading
        </p>
    </div>
</div>

2) After declaring your app level module in your code, add the Response Interceptors for http requests to the configuration block

var app = angular.module('myCoolGridApp', ['ngGrid']);

app.constant('_START_REQUEST_', '_START_REQUEST_');
app.constant('_END_REQUEST_', '_END_REQUEST_');
app.config(['$httpProvider', '_START_REQUEST_', '_END_REQUEST_', function ($httpProvider, _START_REQUEST_, _END_REQUEST_) {
    var $http,
     interceptor = /*see additional details on codingsmackdown.tv*/
    $httpProvider.responseInterceptors.push(interceptor); 
}

3) Lastly, include your loadingWidget directive

app.directive('loadingWidget', ['_START_REQUEST_', '_END_REQUEST_', function (_START_REQUEST_, _END_REQUEST_) {
return {
    restrict: "A",
    link: function (scope, element) {
        element.hide();
        scope.$on(_START_REQUEST_, function () {element.show();});
        scope.$on(_END_REQUEST_, function () {element.hide();});
    }
 };
}]);

For more information, visit codingsmackdown

Answer №2

I had a similar inquiry to yours.

I stumbled upon this helpful tutorial:

The author utilizes vm.loading = true while retrieving data from the server and changes it to false once the process is complete.

var app = angular.module('app', ['ngTouch', 'ui.grid']);

app.controller('MainCtrl', ['$http', '$timeout', function ($http, $timeout) {
  var vm = this;

  vm.reset = reset;
  vm.noData = noData;
  vm.gridOptions = {
    columnDefs: [
      { field: 'name' },
      { field: 'age' }
    ]
  };

  reset();

  ////////////

  // Setting up the data source
  function init() {
    $http.get('data.json')
      .success(function (data) {
        vm.gridOptions.data = data;
      })
      .finally(function () {
        vm.loading = false;
      });
  }

  // Resetting the data source with a delay to show the loading message
  function reset() {
    vm.loading = true;

    vm.gridOptions.data = [];

    $timeout(function () {
      init();
    }, 1000);
  }

  function noData() {
    vm.gridOptions.data = [];
  }
}]);

In the HTML, ng-hide is used to display/hide the spinner depending on the values of gridOptions.data and vm.loading:

<div id="grid1" ui-grid="vm.gridOptions" class="grid">
    <div class="grid-msg-overlay" ng-hide="!vm.loading">
      <div class="msg">
        <span>
          Loading Data...
          <i class="fa fa-spinner fa-spin"></i>
        </span>
      </div>
    </div>
    <div class="grid-msg-overlay" ng-hide="vm.loading || vm.gridOptions.data.length">
      <div class="msg">
        <span>No Data</span>
      </div>
    </div>
</div>

Here is the Plunker where the final version is showcased.

Answer №3

Check out the angularjs-spinner on GitHub at this link

Answer №4

After searching for a solution to my problem, I stumbled upon this answer. However, I needed to display something within the grid itself, so I decided to create my own solution. You can view it here. My approach involves dynamically changing the gridOptions and displaying a loader as a row inside the grid.

loaderOptions = {
        "columnDefs": [{
            "name": "",
            "field": "loading",
            "enableColumnMenu": false,
            "cellTemplate": '<div style="width:90px; margin:auto;"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span>&nbsp;Loading...</div>'
        }],
        "data": [{
            "loading": ""
        }] 
    };

Answer №5

To implement this functionality, include the following code snippet in your HTML section:

<img alt="loading..." src='images/ajax-loader.gif")' /> Displaying loading message...

Additionally, ensure to add the subsequent code in your app.controller script:

 $http.get(yourdataUrl)
   .then(function (response) {
       $scope.records = response.data;
       $("#loadingWidget").hide();
   });

After applying these steps, the feature works perfectly for me!

Answer №6

This is a code snippet in HTML

 <img ng-show="loading" src="~/img/loding.jpg" />
 <div class="ngtyle" ng-grid="myGridView"></div>

This is a code snippet in AngularJS

var app = angular.module('App', ['ngGrid']);
app.controller('MainCtrl', function ( $scope, myService ) {
  $scope.loading = true;

  myService.get().then( function ( response ) {
    $scope.items = response.data;
  })
  .finally(function() {
    $scope.loading = false;
  });

 $scope.myGridView = {
    data: 'dataList',
    columnDefs: 'myDisplayColumns'};
});    

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 abundance of information presented in the "object" type, specifically "[object Object]," prevents serialization as JSON. It is advised to exclusively provide data types that are JSON

Utilizing NextJS, I initially made internal calls to a /api route using fetch(). However, for production, it was evident that internal api calls within getServerSideProps are not allowed. Consequently, I am attempting to directly access my MongoDB database ...

Implementing an ajax search functionality

I am currently working on implementing an AJAX search feature into my project. The application initially displays all client data in a table on the webpage. When something is typed into the search bar, I want the search results to be shown instead of all ...

Sending an AJAX request to submit a form and receiving a response

I am in the process of developing a Rails application and I am seeking a way to submit a form using Ajax. This functionality is crucial as I want the form submission to occur without causing a full page reload. Initially, I tried using form_remote_tag but ...

Is there a way to get an iframe to mimic the behavior of other media elements within a horizontal scrolling container?

Take a look at this code snippet: $(document).ready(function() { $('.scrollable-area').on('wheel', function(e) { var scrollLeft = $(this).scrollLeft(); var width = $(this).get(0).scrollWidth - $(this).width(); var delta ...

Javascript - Issue with Ajax causing additional commas in JSON responses

I'm attempting to send a request to a RESTful server using the HTTP module in Node.js. Due to the large response size (64 chunks, approximately 100kb), the HTTP module combines the chunks into a single string response like this: res.setEncoding(& ...

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

The art of slipping away from a character in JavaScript while adding HTML using jQuery

I am trying to add multiple HTML canvas elements to an existing HTML canvas. <div> <canvas id="BackGroundImage" width="800" height="300" style="position: absolute; z-index: 0;"></canvas> <canvas id="canvas" width= ...

Refreshing a page in Next.js causes query parameters to disappear

I am facing an issue with routing between two components and passing data from the first to the second without sending the parameter in the URL. The problem arises when I refresh the page and the query params are lost. <p className={styles.jobname}& ...

The @ViewChild in Angular 2 seems to be unable to detect the BaseChartDirective from the ng2-charts

I'm currently using ng2-charts v1.5.0 and I'm facing an issue with updating the chart data after a click event. Despite following suggestions from other sources, I am unable to get it to work properly. Here is a snippet of my code: <div styl ...

I have received a JSON multi-line string after entering information in a textarea

I've been working on a small social network project where users can create and share posts. However, I encountered an issue with formatting when storing and displaying the posts. When a user enters text with line breaks in the post creation form, it ...

Utilizing the Current URL from the address bar as a variable to link within the same page

My goal is to: Extract the current URL address from the browser bar, which will have a format like this: http://example.com/test/index.html?&dv1=1023faf2ee37cbbfa441eca0e1a36c Retrieve the lengthy ID number located at the end of the URL 1023faf2ee37c ...

Issue with NodeJS proxy not functioning correctly

The current request route starts at localhost:3001, passes through a proxy located on the same localhost at localhost:3001/proxy, where it is then directed to the Salesforce instance. The ExpressJS proxy and AngularJS client-side app are utilized for this ...

Any ideas on how to potentially establish a default route based on conditions with react-router-dom v6?

Managing two pages, Page1 and Page2, requires conditional configuration for setting one as the homepage based on a specific condition. Additionally, all URLs must be prefixed with an ID. Take a look at the code snippet below: <Routes> <Route pat ...

The database was successfully updated; however, the API encountered a 500 error when trying to access

Currently, I am working on a project that utilizes Javascript alongside Node.js, Express, SuperAgent, and KnexJS for database management with Sqlite3. The issue I am facing is as follows: Upon submitting data for updates through my API route using the PUT ...

Converting a JSON PHP array into Javascript

How can I convert this PHP array named $data into JSON using json_encode? Whenever I try to do so in JavaScript by writing... var myJson = <?php echo json_encode($data) ?>; console.log(myJson); I encounter errors. I am curious about any restrictio ...

Creating a User-friendly Layout for Admin Pages in Next.js Version 13

Hey there, I'm facing an issue with the layout while using Next.js 13 Experimental App Directory. On my website's index page or routes '/', I want to show a landing page and use a specific layout for all pages except for those under the ...

aligning JSON information with JavaScript object

I am currently in the process of setting up a sample dataset in JSON format for a JavaScript tutorial that I'm going through. Here's how the data object looks in JavaScript: app.Book = Backbone.Model.extend({ defaults: { coverImage: ...

Serving Files in Express JS: the benefits of serving files directly from memory compared to serving static

Should I keep images and other assets in memory or serve them from static assets? Will often-requested static assets be stored in memory? Does anyone have insight into the performance implications of this decision? ...

changing font size on a mobile-friendly site using javascript

Currently, I am designing a responsive webpage utilizing Bootstrap framework. Situated in the center of the screen is a text that reads: <p id="entershop" ><a class=no-deco href="shop.html">enter shop</a></p> Within the Bootstra ...

What sets apart the definition of isolated scope variables for an Angular directive when done within {} as opposed to in

When working with Angular directives, I am aware that I can assign an isolated scope by adding '=' or '@' or '&' in the {} to define variables. However, it seems like this is not required within the link function. For example: ...