Tips for incorporating a spinner during content loading within AngularJS

When the user clicks on the "Search" button, content will load and the button label will change to "Searching" with a spinner shown while the content is loading. Once the content has loaded (Promise resolved), the button label will revert back to "Search" and the button will be enabled again.

Although attempted, the below code consistently shows the spinner even after the content has loaded.

HTML :

<button class="btn btn-xs btn btn-blue" ng-click="show()">
  <span><i class="glyphicon glyphicon-off"></i></span> {{buttonLabel}}
</button>

Script :

$scope.buttonLabel = "Search";
$scope.show = function() {
  $scope.buttonLabel = "Searching";
  $scope.test = TestService.getList( $cookieStore.get('url'),
    $rootScope.resourceName+"/students" );
    $scope.test.then( function( data ) {
      if( data.list ) {
        $scope.testData = data.list;
        $scope.buttonLabel = "Search";
      }
    }
  }

Updated Fiddle : http://jsfiddle.net/xc6nx235/18/

Answer №1

<div ng-app="formDemo" ng-controller="LocationFormCtrl">
<div>
    <button type="submit" class="btn btn-primary" ng-click="search()"> 
        <span ng-show="searchButtonText == 'Searching'"><i class="glyphicon glyphicon-refresh spinning"></i></span>
        {{ searchButtonText }}
    </button>
</div>

Utilizing the ng-show or ng-hide directives is all that's required.

ng-show="expression"

<span ng-show="searchButtonText == 'Searching'">
    <i class="glyphicon glyphicon-refresh spinning"></i>
</span>

This particular span will only be visible when the value of searchButtonText matches the string 'Searching'.

It would be beneficial to delve deeper into angular's directives as they can prove helpful in your future endeavors.

Best of luck.

Demo http://jsfiddle.net/xc6nx235/16/

Answer №2

Utilize the ng-show directive to toggle the visibility of the loader with ng-show="test":

JSFiddle

// Visit http://icelab.com.au/articles/levelling-up-with-angularjs-building-a-reusable-click-to-edit-directive/

angular.module("formDemo", [])

.controller("LocationFormCtrl", function ($scope, $timeout) {
$scope.searchButtonText = "Search";
$scope.test="false";
$scope.search = function() {
$scope.test="true";
$scope.searchButtonText = "Searching";
$timeout(function(){
$scope.test="false";
$scope.searchButtonText = "Search";
},1000)
// Add your search functionality here
}
});
body {
font-family:"HelveticNeue", sans-serif;
font-size: 14px;
padding: 20px;
}
h2 {
color: #999;
margin-top: 0;
}
.field {
margin-bottom: 1em;
}
.click-to-edit {
display: inline-block;
}
input {
display: initial !important;
width: auto !important;
margin: 0 5px 0 0 !important;
}

.glyphicon.spinning {
animation: spin 1s infinite linear;
-webkit-animation: spin2 1s infinite linear;
}

@keyframes spin {
from { transform: scale(1) rotate(0deg);}
to { transform: scale(1) rotate(360deg);}
}

@-webkit-keyframes spin2 {
from { -webkit-transform: rotate(0deg);}
to { -webkit-transform: rotate(360deg);}
}
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.1.6/css/foundation.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> 
<script src="https://rawgithub.com/angular-ui/angular-ui/master/build/angular-ui.js"></script>
  
<div ng-app="formDemo" ng-controller="LocationFormCtrl">
    <div>
    <button type="submit" class="btn btn-primary" ng-click="search()">
       <span ng-show="test" ><i class="glyphicon glyphicon-refresh spinning"></i></span>
        {{ searchButtonText }}
    </button>
</div>    
</div>

Answer №3

If you want to keep it simple, you can use this straightforward directive:

https://www.example.com/angular-spinner-demo

All you need to do is include the button-spinner='loading' attribute in your code:

<button class="btn btn-primary" ng-click="display()" button-spinner="loading">Fetch Data</button>

Whenever the value of your loading variable within the scope is set to true, a spinner will be displayed inside the button.

Answer №4

To make your spinner appear, simply include an ng-show directive:

<span ng-show="isLoading"><i class="glyphicon glyphicon-refresh spinning"></i></span>

Also, don't forget to add this functionality in your controller:

.controller("FormController", function ($scope) {
    $scope.buttonText = "Submit";
    $scope.isLoading = false;
    $scope.flag = false;
    $scope.submitForm = function() {
        $scope.flag = true;
        $scope.isLoading = true;
        $scope.buttonText = "Submitting";
        // Carry out form submission here
   }
});

Remember to reset $scope.isLoading back to false once you receive a response.

Check out the demo!

Answer №5

Utilize the ng-show directive in this manner ng-show="test" on the spinner span:

Here is a snippet:

// http://icelab.com.au/articles/levelling-up-with-angularjs-building-a-reusable-click-to-edit-directive/

angular.module("formDemo", [])

.controller("LocationFormCtrl", function($scope) {
  $scope.searchButtonText = "Search";
  $scope.test = "false";
  $scope.search = function() {
    $scope.test = "true";
    $scope.searchButtonText = "Searching";
    // Perform your search functionality here
  }
});
</style> <!-- Ugly Hack due to jsFiddle issue:http://goo.gl/BUfGZ --> 
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.1.6/css/foundation.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> <script src="https://rawgithub.com/angular-ui/angular-ui/master/build/angular-ui.js"></script> <style> body {
  font-family: "HelveticNeue", sans-serif;
  font-size: 14px;
  padding: 20px;
}
h2 {
  color: #999;
  margin-top: 0;
}
.field {
  margin-bottom: 1em;
}
.click-to-edit {
  display: inline-block;
}
input {
  display: initial !important;
  width: auto !important;
  margin: 0 5px 0 0 !important;
}
.glyphicon.spinning {
  animation: spin 1s infinite linear;
  -webkit-animation: spin2 1s infinite linear;
}
@keyframes spin {
  from {
    transform: scale(1) rotate(0deg);
  }
  to {
    transform: scale(1) rotate(360deg);
  }
}
@-webkit-keyframes spin2 {
  from {
    -webkit-transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="formDemo" ng-controller="LocationFormCtrl">
  <div>
    <button type="submit" class="btn btn-primary" ng-click="search()">
      <span ng-show="test"><i class="glyphicon glyphicon-refresh spinning"></i></span>
      {{ searchButtonText }}
    </button>
  </div>
</div>

Answer №6

To toggle the class .spinning depending on the value of $scope.test, it is recommended to utilize the ng-class directive. You can view the modified code in this updated demo: http://jsfiddle.net/xc6nx235/15/

Answer №7

To implement spinner visibility control in Angular2/4, you can utilize the [hidden] attribute. Check out this Plunker example.

<button class="btn btn-primary" (click)="onClickDoSomething()">
  <span [hidden]="!spin">
        <i class="glyphicon glyphicon-refresh spinning"></i>
    </span> Do something
</button>

The spinning animation is defined as follows:

<style>
  .spinning {
    animation: spin 1s infinite linear;
  }

  @keyframes spin {
    from {
      transform: scale(1) rotate(0deg);
    }
    to {
      transform: scale(1) rotate(360deg);
    }
  }
</style>

Your component will simply toggle the boolean value to show or hide the spinner. In this particular demonstration, the spinner spins for a duration of 10 seconds.

import {Component} from 'angular2/core';
import {Observable} from 'rxjs/Rx';

@Component({
  selector: 'do-something',
  templateUrl: 'src/dosomething.html'
})
export class DoSomething {
   private spin: boolean = false;

   onClickDoSomething() {
     this.spin = true;
     this.sub = Observable.interval(10000).subscribe(x => {
         this.sub.unsubscribe();
         this.spin = false;
     }); 
   }
}

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

Obtain the ID of the textarea element when it is clicked

Is there a way to retrieve the id of a textarea that was focused when another element is clicked? I have tried using $(':input:focus').attr('id'), but the textarea quickly loses focus after the click, making it impossible to obtain the ...

Streamline AngularJS conditional statements within a loop

Is there a more efficient way to handle these conditionals in an angularjs controller loop? angular.forEach(vm.brgUniversalDataRecords, function (value) { switch(value.groupValue2) { case 1: vm.graphSwitch1 = value.groupValue3; ...

What is the best way to integrate a new unique identifier into an existing MongoDB document using NodeJS?

I am looking to add up a field in a document when I input a new entry that has a replicated unique id. This is the code I have so far: MongoClient.connect(process.env.MONGODB_URI || process.env.DB_CONNECTION, { useUnifiedTopology: true, useNewUrlParser ...

Exploring Django Crispy Forms and How They Handle Static Files

I have integrated Django Crispy Forms with Twitter-bootstrap by installing crispy forms as per the instructions on this link. However, I am struggling to locate the uni-form files that need to be included in my HTML code. Can anyone provide guidance on ho ...

I am trying to create a login application using angular and ionic, but I am facing an issue with accessing the $stateProvider routing for the login page through the <ion-nav-view> element

index.html Description: The index.html file is the main file containing all the view pages. It includes HTML code for setting up the structure of the application. <!DOCTYPE html> <html ng-app="loginApp"> <head> <meta charset="u ...

Issue with Jquery .scroll method not triggering display:none functionality

Styling Using CSS #acc-close-all, #to-top { position: relative; left: 951px; width: 29px; height: 42px; margin-bottom: 2px; display:none; } #acc-close-all a, #to-top a { position: absolute; float: right; display: block ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

Transform the binary image data sent by the server into an <img> element without using base64 encoding

It's been a challenge trying to find a reliable method for adding custom request headers to img src, so I'm experimenting with manually downloading the image using ajax. Here is an example of the code I am working on: const load = async () => ...

Instead of using a v-if condition, add a condition directly in the Vue attribute

Apologies for the unclear title, as I am unsure of what to name it with regards to my current issue, I am attempting to create a component layout using vuetify grid. I have a clear idea of how to do this conventionally, like so: <template> <v-fl ...

What are the steps to create two frames using Twitter Bootstrap?

I'm just starting to work with Twitter Bootstrap and I need some help. Can someone assist me in creating a two-column layout inside the HTML, where the menu in the header stays visible even when scrolled down? I've included my HTML code below. Th ...

Combining an Editor and Dropdown Feature for a Single Attribute in Asp.Net MVC

How can I implement both an Editor and a Dropdown list for a single field? In the scenario where an agency is not already in the database, the user should be able to enter the agency name. Otherwise, the value should be selected from a dropdown list. I n ...

Implementing pagination in React: A step-by-step guide

I am fetching data from the GitHub API, specifically from here Although I have all the necessary data to display, I want to limit it so that only 20 repositories are shown per page. In addition, I prefer not to use any frameworks or plugins for this task ...

The error message is failing to display the mat error

I've implemented the Mat control date range input control in my project and I'm facing an issue regarding displaying an error message when the user forgets to enter either the start date or end date. Below is the HTML code: <mat-form-field> ...

My mongoose sort function doesn't seem to be functioning properly. What could be the issue?

Hey there! I've got a simple API up and running on Node.js, using MongoDB as my database with Mongoose for querying. The issue I'm facing is related to sorting data using the mongoose 'sort' method. Instead of behaving as expected, it s ...

Selecting radio buttons using Bootstrap and JavaScript

I'm interested in incorporating this bootstrap radio selection feature into my JavaScript code. For example, if option1 is true, I want to execute a specific action... How can I achieve this? <div class="alert alert-info" role="alert"> < ...

Is there a way to extract just the date portion from the string "2017-11-13T00:00:00" using AngularJS?

I am looking for a way to extract only the date portion from "2017-11-13T00:00:00" using AngularJS. I attempted to achieve this using the following method: &scope.date = "2017-11-13T00:00:00"; var dateParts = $filter('date')(new Date(&sc ...

What is the best method to extract data from a specific member of a list within a dictionary with AngularJS?

Within my dictionary, the structure is as follows : Dictionary<string,List<B>> a; The class B has the following format: public class B { public Int64 c; public Boolean d; } Upon performing backend processing, I have obtained a wit ...

Updating the values of parent components in Vue.js 3 has been discovered to not function properly with composite API

Here is a Vue component I have created using PrimeVue: <template lang="pug"> Dialog(:visible="dShow" :modal="true" :draggable="false" header="My Dialog" :style="{ width: '50vw' }" ...

The router.navigate() function seems to be malfunctioning as it is not working as

I have a method defined as follows: private redirect(path: string): void { this.router.navigate([path]); } This method is called within another method like so: private onError(error: any): void { switch (error.status) { case 401: / ...

What is the best way to change a date from the format DD/MM/YYYY to YYYY-MM-DD

Is there a way to use regular expressions (regex) to convert a date string from DD/MM/YYYY format to YYYY-MM-DD format? ...