How to do preloader for `ng-view` in Angular JS?

后端 未结 3 1114
攒了一身酷
攒了一身酷 2021-01-07 00:21

I use

on web page. When I click link in block
is loaded HTML template was set in routeProvider
3条回答
  •  再見小時候
    2021-01-07 00:51

    It seems that there are some similar questions here:

    • Angularjs loading screen on ajax request
    • Angular JS loading screen and page animation.

    Also, there a bunch of modules to work with loading animation at http://ngmodules.org. For example, these:

    • https://github.com/cgross/angular-busy
    • https://github.com/chieffancypants/angular-loading-bar (I use this one in my apps)
    • https://github.com/McNull/angular-block-ui and other.

    UPD: I've written a simple solution based on how the angular-loading-bar works. I didn't test it with ng-view, but it seams to work with ui-view. It is not a final solution and have to be polished.

    angular.module('ui')
    
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.interceptors.push('LoadingListener');
    }])
    
    .factory('LoadingListener', [ '$q', '$rootScope', function($q, $rootScope) {
        var reqsActive = 0;
    
        function onResponse() {
            reqsActive--;
            if (reqsActive === 0) {
                $rootScope.$broadcast('loading:completed');
            }
        }
    
        return {
            'request': function(config) {
                if (reqsActive === 0) {
                    $rootScope.$broadcast('loading:started');
                }
                reqsActive++;
                return config;
            },
            'response': function(response) {
                if (!response || !response.config) {
                    return response;
                }
                onResponse();
                return response;
            },
            'responseError': function(rejection) {
                if (!rejection || !rejection.config) {
                    return $q.reject(rejection);
                }
                onResponse();
                return $q.reject(rejection);
            },
            isLoadingActive : function() {
                return reqsActive === 0;
            }
        };
    }])
    
    .directive('loadingListener', [ '$rootScope', 'LoadingListener', function($rootScope, LoadingListener) {
    
        var tpl = '
    Loading...
    '; return { restrict: 'CA', link: function linkFn(scope, elem, attr) { var indicator = angular.element(tpl); elem.prepend(indicator); elem.css('position', 'relative'); if (!LoadingListener.isLoadingActive()) { indicator.css('display', 'none'); } $rootScope.$on('loading:started', function () { indicator.css('display', 'block'); }); $rootScope.$on('loading:completed', function () { indicator.css('display', 'none'); }); } }; }]);

    It can be used like this:

提交回复
热议问题