I make an $http
request when a user clicks a <button>
and I disable/hide/show several elements on screen until the request comes back with either success
or error
Is there a way to know that $http
hasn't had a response yet? The way I am doing it right now is I have a var in my controller called $scope.requesting
which I then use in my HTML page like so:
<img src="img/loader.gif" ng-show="requesting" />
so basically when $scope.requesting
is true, show the spinning ajaxyish loader.
I'd like to ditch the $scope.requesting
if possible and use whatever $http
has to offer, if any at all.
Login Controller
function LoginForm($scope, $http)
{
$scope.requesting = false;
$scope.login = function()
{
$scope.requesting = true;
$http.post('resources/request.php', data, {timeout:20000})
.success(function(data, status, headers, config)
{
$scope.requesting = false;
})
.error(function(data, status, headers, config)
{
$scope.requesting = false;
}
);
}
}
You can make use of
$http.pendingRequests
array of config objects for currently pending requests. It is possible to use it that way:Try this directive: https://github.com/afeiship/angular-isloading
css:
html:
javascript:
description:
<!--1.attach the directive-->
<!--2.write the scope.loading to the app.$rootScope-->
<!--2.read loading props for CSS-->
this jsbin project takes @DmitryEvseev's answer to the next step. It provides finer control over which requests can be used to trigger "loading...".
Those requests with
{ showLoader: true }
are used to show the 'loading...' panel.HTML
Javascript
None of the answers here really nailed it for me, and I shun using
$http.pendingRequests
, so here's what I've doneMy use case was that I had to show a simple "Loading.." message on the top of my viewport if I had any in-flight requests doing things on the server.
Inside
.config
, I've registered a new Interceptor. and inside there I've added a simple counter that increments by 1 per request and decrements per response.