Adding Spinable Button To Your Angular App

A spinner to appear on the button when it is clicked and disappear when underlying job is done, is really a cool idea. Suppose on clicking a button , you are calling a web service and it might take few seconds to get back the response. In such scenario, showing a spinner on the button  during that period will improve the user experience.

Here are the 7 steps to implement it in your angular app.

Step 0 : State of  your initial code

// in your html

<button ng-click="submit()">Submit</button> 

// in your angular controller

$scope.submit = function(){
  // code to call web service
};

$scope.onSubmitSuccess = function(){
  // handle service call success
};

$scope.onSubmitError = function(){
  // handle service call error
};


Step 1: Import font awesome.css to your html

<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">

Note : You can also download font-awesome to your own server and can point to it.

Step 2: Update your button with the following style

<button ng-click="submit()">Submit
    <i class="fa fa-spinner fa-spin"></i>
</button>

Step 3: Add a variable in your angular controller

$scope.workInPorgress = false;

Step 4: Update the variable value when job starts

$scope.submit = function(){
    $scope.workInProgress = true;
  //code to call web service
}

Step 5: Update the variable value when job ends (success/failure)

$scope.onSubmitSuccess = function(data){
    $scope.workInProgress = false;
  //handle service call success
}

$scope.onSubmitError = function(error){
    $scope.workInProgress = false;
  //handle service call error
}

Step 6: Apply conditional appering of spinner

<button ng-click="submit()">Submit
    <i ng-if="workInProgress" class="fa fa-spinner fa-spin"></i>
</button>


Happy Spinning !!!

1 comment: