在$ HTTP / $ Q电话angularjs禁用按钮 [英] angularjs disable button on $http/$q calls
问题描述
继DRY校长,我想写这使为$持续时间内禁用按钮一个按钮指令HTTP类。
following the DRY principal, i want to write a button directive which keeps button disabled for the duration of $http class.
我想这样做,以便从点击按钮多次禁止用户,但我不能够去思考如何让一个指令内部功能的承诺的地位,因为该功能驻留在$范围
I want to do this so as to forbid user from clicking the buttons multiple times, but i am not able to think on how to get function promise status inside a directive, given that the function resides on $scope
的情况是非常通用,按键NG-点击不会调用一个函数,它反过来又使$ HTTP调用。用户点击:按钮,应该禁用和$ HTTP调用得到解决后,才应启用,无论是成功还是失败。
the scenario is very generic, buttons ng-click does call a function which in turn makes $http calls. on user click : button should get disabled and should be enabled only after the $http call is resolved, either success or failure.
推荐答案
虽然我会小心过度工程的一个办法做到这一点是通过使用自定义指令。该指令
Although I would be careful of over-engineering, a way to do this would be by using a custom directive. This directive
- 接受一个选项,通过属性的范围内传递的函数,那必须返回一个承诺
- 在点击按钮,调用这个函数,并禁用按钮
- 在
最后
的承诺,它会重新启用按钮
- Accepts an option, passed by attribute, of a function in the scope that must return a promise
- On click of the button, calls this function, and disables the button
- On
finally
of the promise, it re-enables the button
-
app.directive('clickAndDisable', function() {
return {
scope: {
clickAndDisable: '&'
},
link: function(scope, iElement, iAttrs) {
iElement.bind('click', function() {
iElement.prop('disabled',true);
scope.clickAndDisable().finally(function() {
iElement.prop('disabled',false);
})
});
}
};
});
这可以在一个按钮被用作如下:
This can be used on a button as follows:
<button click-and-disable="functionThatReturnsPromise()">Click me</button>
您可以在<一个动作中看到这个href=\"http://plnkr.co/edit/YsDVTlQ8TUxbKAEYNw7L?p=$p$pview\">http://plnkr.co/edit/YsDVTlQ8TUxbKAEYNw7L?p=$p$pview ,在返回的承诺的功能是:
You can see this in action at http://plnkr.co/edit/YsDVTlQ8TUxbKAEYNw7L?p=preview , where the function that returns the promise is:
$scope.functionThatReturnsPromise = function() {
return $timeout(angular.noop, 1000);
}
但你可以取代 $超时
通过调用 $ HTTP
,或从返回的任何服务功能一个承诺。
But you could replace $timeout
with a call to $http
, or a function from any service that returns a promise.
这篇关于在$ HTTP / $ Q电话angularjs禁用按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!