Symon Kt Symon Kt - 4 months ago 26
AngularJS Question

How to disable buttons until http request is processed/loaded in AngularJS?

I want to write a directive that keeps a button and page disabled for the duration of the http request.


  • If I update or submit a form, the button will disable until the http
    response is complete.

  • When a page is loading, it will disable until the entire data is
    loaded from the server.

  • After 10 seconds, the button will be active and the user can click
    multiple times.



app.js

<script>
var angModule = angular.module("myApp", []);

angModule.controller("myCtrl", function ($scope, $timeout) {
$scope.isSaving = undefined;
$scope.btnVal = 'Yes';
$scope.save = function()
{
$scope.isSaving = true;

$timeout( function()
{
$scope.isSaving = false;

}, 1000);
};
});
</script>


index.html

<div ng-app="myApp">
<ng-form ng-controller="myCtrl">
Saving: {{isSaving}}

<button ng-click="save()" ng-disabled="isSaving">
<span ng-hide="isSaving">Save</span>
<span ng-show="isSaving">Loading...</span><i class="fa fa-spinner fa-spin" ng-show="isSaving"></i>
</button>


</ng-form>
</div>


I am new to AngularJS, please help me write a directive for this.

Answer

here a basic example :

<button ng-click="save()" loading="Loading..." notloading="save" disableonrequest>

myApp.directive("disableonrequest", function($http) {
  return function(scope, element, attrs) {
    scope.$watch(function() {
      return $http.pendingRequests.length > 0;
    }, function(request) {
      if (!request) {
        element.html("<span >"+attrs.notloading+"</span>");
      } else {
        element.html("<span >"+attrs.loading+"</span><i class='fa fa-spinner fa-spin'></i>");
      }
    });
  }
});

A WORKING EXAMPLE