Created
August 6, 2013 17:03
-
-
Save doup/6166407 to your computer and use it in GitHub Desktop.
Example of AngularJS $http loading global variable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- use $root.loading --> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.config(['$httpProvider', function ($httpProvider) { | |
$httpProvider.responseInterceptors.push(['$q', '$rootScope', function($q, $rootScope) { | |
return function (promise) { | |
return promise.then(function (response) { | |
// Success | |
$rootScope.loadingCount--; | |
$rootScope.loading = $rootScope.loadingCount !== 0; | |
return response; | |
}, function (response) { | |
// Error | |
$rootScope.loadingCount--; | |
$rootScope.loading = $rootScope.loadingCount !== 0; | |
return $q.reject(response); | |
}); | |
}; | |
}]); | |
}]); | |
app.run(['$http', '$rootScope', function ($http, $rootScope) { | |
$rootScope.loadingCount = 0; | |
$rootScope.loading = false; | |
$http.defaults.transformRequest.push(function (data) { | |
$rootScope.loadingCount++; | |
$rootScope.loading = $rootScope.loadingCount !== 0; | |
return data; | |
}); | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment