Search code examples
javascriptangularjshtmlloaderangular-directive

how to put loader during loading html and js in angularjs


During the js and html load. I have to put loader. so can I implement that any idea.

How do I have AngularJS show a loading spinner until the data has finished loading?

Currently data is come from local array.


Solution

  • You can make a directive, inject there http service and watch on its request pending:

    (function() {
        'use strict';
        angular
            .module('yourApp')
            .directive('loader', loader);
    
        /**
         * Defines loading spinner behaviour
         *
         * @param {obj} $http
         * @returns {{restrict: string, link: Function}}
         */
        function loader($http) {
            return {
                restrict: 'A',
                link: function(scope, element, attributes) {
                    scope.$watch(function() {
                        return $http.pendingRequests.length;
                    }, function(isLoading) {
                        if (isLoading) {
                            $(element).show();
                        } else {
                            $(element).hide();
                        }
                    });
                }
            };
        }
    })();
    

    And use it:

    <span class="spinner" data-loader></span>