我忘了我在哪裏找到這段代碼,但它對我很好。
您可以使用對$httpProvider
進行設置。
angular.module("app", [])
.constant('_START_REQUEST_', '_START_REQUEST_')
.constant('_END_REQUEST_', '_END_REQUEST_')
.config(['$httpProvider', '_START_REQUEST_', '_END_REQUEST_', function ($httpProvider, _START_REQUEST_, _END_REQUEST_) {
var $http,
interceptor = ['$q', '$injector', function ($q, $injector) {
var rootScope, location;
function success(response) {
// get $http via $injector because of circular dependency problem
$http = $http || $injector.get('$http');
// don't send notification until all requests are complete
if ($http.pendingRequests.length < 1) {
// get $rootScope via $injector because of circular dependency problem
rootScope = rootScope || $injector.get('$rootScope');
// send a notification requests are complete
rootScope.$broadcast(_END_REQUEST_);
}
return response;
}
function error(response) {
// get $http via $injector because of circular dependency problem
$http = $http || $injector.get('$http');
// don't send notification until all requests are complete
if ($http.pendingRequests.length < 1) {
// get $rootScope via $injector because of circular dependency problem
rootScope = rootScope || $injector.get('$rootScope');
// send a notification requests are complete
rootScope.$broadcast(_END_REQUEST_);
}
return $q.reject(response);
}
return function (promise) {
// get $rootScope via $injector because of circular dependency problem
rootScope = rootScope || $injector.get('$rootScope');
// send notification a request has started
rootScope.$broadcast(_START_REQUEST_);
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
}])
// Loading directive
.directive('loadingWidget', ['_START_REQUEST_', '_END_REQUEST_', function (_START_REQUEST_, _END_REQUEST_) {
return {
restrict: "A",
link: function (scope, element) {
// hide the element initially
element.hide();
scope.$on(_START_REQUEST_, function() {
// got the request start notification, show the element
element.show();
});
scope.$on(_END_REQUEST_, function() {
// got the request end notification, hide the element
element.hide();
});
}
};
}])
而在你的主HTML頁面,只是聲明你的加載內容
<div id="loadingWidget" loading-widget>
<div class="loadingContent">
<p>
Loading ...
</p>
</div>
</div>