im trying to implement some type of a angularjs directive using TYPESCRIPT that will wrap every $http get request with a boolean parameter "isShow" that will watch the state of the request and update the parameter and show/hide the html element accordingly ( Without the use of $scope or $watch. ) Any idea how to achieve this? Thank you
Asked
Active
Viewed 473 times
2 Answers
1
Use the promise disposer pattern:
var spinnerSemaphore = 0;
function own(fn){
spinnerSemaphore++;
var res = $q.when(fn());
fn().then(function(){ spinnerSemaphore--; },
function(){ spinnerSemaphore--; });
return res;
}
Which would let you do:
own(function(){
return $http.get(...);
});
own(function(){
return $http.get(...);
});
own(function(){
return $http.get(...);
});
own(function(){
return $timeout(...); // this also works, and anything else with promises
});
And bind showing the spinner to spinnerSemaphore
(so falsey on 0 means hiding the spinner and more than 0 for showing it).

Community
- 1
- 1

Benjamin Gruenbaum
- 270,886
- 87
- 504
- 504
-
1that's a nice answer benji – phenomnomnominal Oct 07 '15 at 19:07
-
2@phenomnomnominal thanks Craig, I was thinking of you when I wrote it. Also every other minute since then. – Benjamin Gruenbaum Oct 07 '15 at 19:09
-
Benjamin,do i need some kind of a watch for the app to identify that the value of spinnerSemaphore was changed ? – Basilf Oct 08 '15 at 09:53
-
@Basilf no, no need to do weird `$apply` stuff, angular promises already take care of that for you, you just have to bind to `spinnerSemaphore` which will define a watcher for you. – Benjamin Gruenbaum Oct 08 '15 at 10:04
-
i see, it's just that the value for the ng-show for some reason does not get updated... hmmm.. – Basilf Oct 08 '15 at 10:30
-
I don't understand `fn.then(...)`. – Roamer-1888 Oct 09 '15 at 05:02
0
If you are looking for a single spinner you can do that quite easily by binding its ng-show
(or something equivalent) to $http.pendingRequests.length
. Ofcourse this assumed you have $http
in scope (or $rootScope
).

basarat
- 261,912
- 58
- 460
- 511
-
-
Then put it on the root controller and use it like `rootCtrl.$http` ;) – basarat Oct 08 '15 at 23:02