22

How do I change the text on a submit-button while saving data in a form?

I have a button like this

<button ng-click="save()">Save data</button>

and I updated my save-function based on the answers below:

    $scope.ButtonText = "Save day";
    $scope.save=function(){
        $scope.ButtonText = "Saving day";
        for(var i=0;i<days.length;i++)
        {
           MyService.saveday()
            .success(function(data, status, headers, config) {
            })
            .error(function(data, status, headers, config) {
            });
        }
       $scope.ButtonText = "Save day";
    };

While saving data, I would like to change the text from "Save data" to "Saving data" and back to "Save data" when the data has been saved.

UPDATE

I added

 $scope.ButtonText = "Save day"; 

based on the answers below, but realized that my needs are more complex since I am calling an asynchronous service multiple times. So I guess the question is how I can set the text while the service is being called asynchronously and only revert it back to the original text, after all, calls to the service have finished executing.

thanks

Thomas

2 Answers 2

36

You can expose the button text in the scope, and then update the scope value while saving:

<button ng-click="save()">{{button}}</button>

and in your function:

$scope.button = "Save data";

$scope.save=function(){
    $scope.button = "Saving day";
    for(var i=0;i<days.length;i++)
    {
       MyService.saveday()
        .success(function(data, status, headers, config) {
        })
        .error(function(data, status, headers, config) {
        }).then(function() {
            if (i===days.length) { // is the last iteration
                $scope.button = "Save day";
            }
        });
    }

};
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. It worked but I realised my needs were a bit more complicated. I have updated the question to reflect this
I updated my answer, using a promise with then (supposing your service is an http service alias), where at the last iteration the $scope.ButtonText is updated to the original "Save day".
5

There are at least a few ways.

One of the ways is to create another property on a scope, which will hold text of the button.

$scope.buttonText = 'Save';
$scope.save = function() {
    $scope.buttonText = 'Saving...';
};

Then instead of hardcoding button text in HTML bind it to a new scope property.

<button ng-click="save()">{{buttonText}}</button>

1 Comment

thanks. It worked but I realised my needs were a bit more complicated. I have updated the question to reflect this

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.