angularjs disable button on $http/$q calls

前端 未结 9 770
失恋的感觉
失恋的感觉 2021-02-03 10:12

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

9条回答
  •  既然无缘
    2021-02-03 10:59

    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:

    
    

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

    But you could replace $timeout with a call to $http, or a function from any service that returns a promise.

提交回复
热议问题