Angular通用指令/控制器在检测到任何ajax请求后禁用按钮

时间:2017-08-16 15:28:39

标签: angularjs

我看过很多关于这个主题的帖子,但没有具体说明这个问题。

我想知道AngularJs中是否存在通用指令/控制器来禁用按钮(调用ajax请求)并在请求结束后重新启用它。

我使用了“generic”这个词,因为我在特定的ajax请求之后看到了一些使用回调的解决方案,但这不是我需要的。

我需要: 当点击按钮时,按钮调用ajax请求,它将被禁用,直到请求结束。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

这是一种可能性。

您可以将http服务调用视为承诺。一旦http服务调用完成,它将调用链中的下一个promise(如果有的话)。

你可以在一个指令中接收一个函数,然后对它进行包装调用并将另一个函数链接到它。因此,通过这种方式,您可以了解承诺何时执行以及何时履行承诺。

您需要确保重新调整控制器中的承诺。然后将该函数传递给指令。

检查以下示例

https://codepen.io/bbologna/pen/zdpxoB

JS

var app = angular.module('testApp', []);

app.factory('fakeHttpService', ['$timeout', function($timeout){
  var doSomething = function(value) {
    return new Promise(function(resolve, reject) {
        $timeout(() => { resolve(value + 1); $timeout() }, 1000);
        })
    }
  return { doSomething: doSomething }
}])

app.controller('sampleController', ['$scope', 'fakeHttpService', 
    function($scope, fakeHttpService) {
        $scope.doSomething = function(value){
        return fakeHttpService.doSomething(value);
    }
    }
])

app.directive('buttonAsync', function(){
    return {
    restrict: 'E',
    template: `<button ng-click="excecute()" ng-disabled="disabled">DO</button>`,
    scope: {
        on : '&'
    },
    controller : ['$scope', function($scope) {
        $scope.disabled = false;
        $scope.excecute = function() {
        $scope.disabled = true;
        $scope.on()
            .then(function() {
            $scope.disabled = false;
          })
      }
    }]
  }
})

<强> HTML

<div ng-app="testApp" ng-controller="sampleController">
  <button-async on="doSomething(3)"></button-async>
</div>