angularjs disable button on $http/$q calls

前端 未结 9 768
失恋的感觉
失恋的感觉 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 11:03

    I was trying different approaches including directives and came up with a simple filter that transforms promise to status object. You can then use the status object to disable related button (or anything else) as well as show some progress messages. So the filter code is:

    function promiseStatus() {
      return function(promise) {
        var status = {
          inProgress: true,
          resolved: false,
          rejected: false
        };
        promise
          .then(function() {
            status.resolved = true;
          })
          .catch(function() {
            status.rejected = true;
          })
          .finally(function() {
            status.inProgress = false;
          });
        return status;
      }
    }
    

    Suppose you have controller like this

    function SubmitController($http) {
      var vm = this;
    
      vm.submitData = function() {
        return $http.post('....')
          .then(function() {
            //Doing something usefull
          });
      }
    }
    

    Then the template will be like this

    
    Submitting...
    Submitted succsssfully!
    Failed to submit!
    

    Full source code is on a Github

提交回复
热议问题