How to Create a Loader in AngularJS

1. HTML (index.html)

html

2. AngularJS Logic (angular.js)

javascript

3. Explanation & Best Practices

  • ng-show="vm.loading": Toggles the loader overlay. You can switch to ng-if if you want DOM removal instead of visibility toggling.

  • Interceptor (loaderInterceptor): Automatically shows the loader on every $http request and hides it when the response returns or errors. This centralizes loader logic for AJAX calls.

  • Manual control: doManualAction() demonstrates how to explicitly show/hide the loader when not using $http (e.g., processing logic).

  • Debounce/hide delay: A slight delay on hide prevents flicker if requests are extremely fast.

  • Fallback GIF: Uncomment the GIF image line if you prefer using an animated GIF instead of the Font Awesome spinner.

4. Optional Enhancements

  • Add a global spinner service event bus so non-controller code can trigger the loader.

  • Replace setInterval sync with $scope.$watch or use a binding via $rootScope/$broadcast for cleaner syncing.

  • Support multiple simultaneous requests by maintaining a counter instead of a boolean (increment on request, decrement on response, show while count > 0).

 

Full Code of Create Angular Loading

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top