Reputation:
I have a form on my application with a button for retrieve. When a user clicks the button then data is retrieved. This could be almost instant or take several seconds. What I would like is for the button to be disabled if the retrieve has been in progress for more than 1 second. Here's what I have so far:
In my application controller:
this.state = {};
In a child controller:
this.retrieve = function () {
app.state.get = true;
$http({
url: '/api/TestData',
method: "GET"
}).success(function (result) {
app.state.get = false;
});
};
In the HTML I have:
<button ng-disabled="app.state.get"
ng-click="test.retrieve()">
Retrieve
</button>
<button ng-disabled="app.state.get">
Another button
</button>
<button ng-disabled="app.state.get">
Another button
</button>
There's more to the application but this is the basics of what I have. Note that I actually have a few buttons and controls and I would like them all to be disabled.
I now I could use something like a request interceptor but the problem I am trying to address is how can I put some delay on the disabling of the buttons and other controls.
Any help and suggestions thanks in advance.
Upvotes: 0
Views: 568
Reputation: 29739
There is an alternative to disabling the button:
Underscore has great utils to do that. The method is called throttle()
.
Example:
var getData = function () {
app.state.get = true;
$http({
url: '/api/TestData',
method: "GET"
}).success(function (result) {
app.state.get = false;
});
};
this.retrieve = _.throttle(getData, 1000);
Now, the method will only be executed at most once per second, no matter how often someone clicks on the button. The first request will be made immediately.
Upvotes: 0
Reputation: 20751
Try using: $timeout
Angular's wrapper for window.setTimeout
. The fn
function is wrapped into a try/catch block and delegates any exceptions to $exceptionHandler
service.
$timeout(fn[, delay][, invokeApply]);
A Sample Example is here
If you want to disable the button after 3 seconds try like
Script
$http({
url: '/api/TestData',
method: "GET"
}).success(function (result) {
$timeout(function(){app.state.get = false}, 3000);
});
But as what @Alp said, why do you need to delay the button disabling
Upvotes: 1