4

In a non-angular application that uses bootstrap and jquery, I can create buttons like this:

<button id="saveButton" data-loading-text="Please wait...">Save</button>

Then, when the button is clicked, I can set it to it's loading state like this:

$('#saveButton').button('loading');

Clicking this button also fires an ajax request, and in the callback for that request, I can reset the button like this:

$('#saveButton').button('reset');

How can I accomplish this same behavior within an angular application? The application also includes Jquery and Bootstrap.

2 Answers 2

13

The advantage of using data-loading-text is to keep the HTML out of the controller. Instead of swapping the text in a controller function, use ng-show and ng-hide inside the button:

<button>
    <span ng-hide="saving">Save</span>
    <span ng-show="saving">Please wait...</span>
</button>

In the controller, set $scope.saving to true or false.

$scope.saving = false;
$scope.save = function() {
    $scope.saving = true;
    // Do your saving here
    $scope.saving = false;
}

If you want to disable the button while it is loading, use ng-disabled. To use a spinning FontAwesome icon, replace the <span> with the <i> tag as shown here:

 <button ng-disabled="saving">
    <span ng-hide="loading">Save</span>
    <i class="fa fa-spinner fa-spin" ng-show="saving"></i>
</button>
Sign up to request clarification or add additional context in comments.

Comments

3

In your angularjs application, inside your view:

<div>
    <button type="submit" class="btn btn-primary" ng-click="search()">{{ searchButtonText }}
    </button>
</div>

In the controller:

$scope.searchButtonText = "Search";

$scope.search = function() {
     $scope.searchButtonText = "Searching";
    // Do your searching here
}

Here is the fiddle Hope this is what you want to implement.

4 Comments

This works, but seems like it could get messy quickly in a large application with lots of buttons as well as additional behavior that needs to occur during and after the saving process. Having to constantly put the application in a loading and non-state seems complicated. I was hoping to find a way to solve this using directives. I will mark your answer as accepted and ask a new question specifically about directives.
Yes, you can use this way if you have few buttons on a page. If you wish, you can create custom directive according to your requirement.
is not just changing the text is also disabling the button.
Have the the same issue like OP. This is some sort of solution. But if you want to use also html inside the searchButtonText e.g. a loader icon. Then this doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.