$http/$q 调用上的angularjs 禁用按钮 [英] angularjs disable button on $http/$q calls

查看:25
本文介绍了$http/$q 调用上的angularjs 禁用按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循 DRY 原则,我想编写一个按钮指令,在 $http 类期间保持按钮禁用.

following the DRY principal, i want to write a button directive which keeps button disabled for the duration of $http class.

我想这样做是为了禁止用户多次单击按钮,但我无法考虑如何在指令中获取函数承诺状态,因为该函数驻留在 $scope 上

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-click 确实调用了一个函数,而该函数又进行了 $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

  • 接受范围内必须返回承诺的函数的通过属性传递的选项
  • 点击按钮时,调用此函数并禁用按钮
  • 在承诺的finally上,它重新启用按钮
  • 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>

您可以在 http://plnkr.co/edit/YsDVTlQ8TUxbKAEYNw7L?p=preview ,其中返回承诺的函数是:

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);
} 

但是您可以将 $timeout 替换为对 $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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆