Symon Kt Symon Kt - 1 year ago 127
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.


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

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

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

}, 1000);


<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>


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

Answer Source

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download