---
title: "angular http请求加上overlay"
author: "Notebookdong"
date: "2016-03-29T22:29:07Z"
tags: []
categories: ["Web前端"]
slug: "angular-http-overlay"
draft: false
lastmod: "2016-03-29T22:29:07Z"
id: 2287291
url: "https://notebookdong.iteye.com/blog/2287291"
---

```
module.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push(function ($q, $rootScope) {
        if ($rootScope.activeCalls == undefined) {
            $rootScope.activeCalls = 0;
        }

        return {
            request: function (config) {
                $rootScope.activeCalls += 1;
                return config;
            },
            requestError: function (rejection) {
                $rootScope.activeCalls -= 1;
                return rejection;
            },
            response: function (response) {
                $rootScope.activeCalls -= 1;
                return response;
            },
            responseError: function (rejection) {
                $rootScope.activeCalls -= 1;
                return rejection;
            }
        };
    });
}]);

module.directive('loadingSpinner', function ($http) {
    return {
        restrict: 'A',
        replace: true,
        template: '<div class="loader unixloader" data-initialize="loader" data-delay="500"></div>',
        link: function (scope, element, attrs) {

            scope.$watch('activeCalls', function (newVal, oldVal) {
                if (newVal == 0) {
                    $(element).hide();
                }
                else {
                    $(element).show();
                }
            });
        }
    };
});
```

 原文：http://stackoverflow.com/questions/17144180/angularjs-loading-screen-on-ajax-request?answertab=votes#tab-top