The button transforms once the user submits the form

I have two buttons labeled "Save" and "Saving..."

<div ng-switch on="isLoading">
 <div ng-switch-when="true">
  <button type="button" class="btn btn-primary btn-block disabled">Saving ...</button>
 </div>

 <div ng-switch-when="false">
  <button type="submit" class="btn btn-primary btn-block" ng-disabled="!allowSubmit(addUser)" ng-click="add();">Save</button>
 </div>
</div>

My goal is to keep the button as 'Save' until the user clicks it, at which point it will change to 'Saving...' for a brief moment. I attempted using $timeout but it ended up delaying the entire form submission by 2 seconds.

    $dialogScope.add = function() {
                if ($dialogScope.user.password != $dialogScope.user.confirmpassword && $dialogScope.user.username) {
                    $dialogScope.hasError = true
                    $dialogScope.errorMessage = "Password does not match";
                    return $dialogScope.errorMessage;
                }
                var copy = angular.copy($dialogScope.user);
            }
            $timeout(function() {
                $dialogScope.hasError = false;
                $scope.users.push(copy);
                $dialogScope.closeThisDialog();
            }, 2000);

Any suggestions on how to achieve this without delaying the form submission?

Answer №1

Frankly speaking, I haven't had the chance to test it yet but a similar approach should do the trick.

$dialogScope.add = function() {
    if ($dialogScope.user.password != $dialogScope.user.confirmpassword &&
      $dialogScope.user.username) 
    {
        $dialogScope.hasError = true
        $dialogScope.errorMessage = "Password does not match";
        return $dialogScope.errorMessage;
    }
    var copy = angular.copy($dialogScope.user);

    $dialogScope.hasError = false;
    $scope.users.push(copy);
    $dialogScope.closeThisDialog();
    $scope.isLoading = true;

    $timeout(function() {
        $scope.isLoading = false;
    }, 2000);
}

If you have any feedback, please feel free to share.

Answer №2

Ng-switch might not be needed in this case.

Here is an alternative approach:

HTML:

<div ng-switch-when="true">
  <button type="button" class="btn btn-primary btn-block disabled">{{btnText}}</button>
</div>

JS:

$dialogScope.btnText = 'save';
$dialogScope.add = function() {
                if ($dialogScope.user.password != $dialogScope.user.confirmpassword && $dialogScope.user.username) {
                    $dialogScope.hasError = true
                    $dialogScope.errorMessage = "Password doesn't match";
                    return $dialogScope.errorMessage;
                }
                var copy = angular.copy($dialogScope.user);
                $dialogScope.btnText = 'saving...';
            }
            $timeout(function() {
                $dialogScope.hasError = false;
                $scope.users.push(copy);
                $dialogScope.closeThisDialog();
                $dialogScope.btnText = 'save';
            }, 2000);

Answer №3

To implement a loading icon while saving data, the button should display "Saving" during processing. This can be achieved by using a variable in your code.

Here is an example:

Before Button Click

$scope.loading = false;

On Button Click

$scope.loading = true;

HTML

<button type="submit" ng-disabled="myForm.$invalid">    
    <span data-ng-hide="loading"><i class="fa fa-save"></i>Save</span>
    <span data-ng-show="loading"><i class="fa fa-refresh fa-spin"></i>Saving</span>    
</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Passport Google Oauth login redirection to successful route

I am currently following a tutorial on setting up Google Oauth in my Express app using Passport.js. The tutorial can be found here. Below are the routes defined in my server.js file: // Code snippet here The server.js file also imports configurations fro ...

Accessing a constant injected into an AngularJs controller from the controller's view: best practices

In my application's app.js, I have the following code: (function () { angular.module('routerDemo', [ 'ui.router', // Routing ]) })(); angular.module('routerDemo').constant('cons ...

Sophisticated method in JavaScript to conceal and reveal div elements

My knowledge of front-end web development is strongest in HTML and CSS, but when it comes to JavaScript, I feel like there must be a more efficient way to achieve the functionality I want. On my website, I have a set of <li> items that, when clicked ...

Tools needed for Angular project development

Currently, I am engaged in a project using AngularJS on a Windows 7 computer. My desire is to be able to seamlessly transition between working at the office and working from home or any other location. If I have everything installed in a folder named C:/C ...

Tips for overriding ng-disable in AngularJSUnleashing the

This is a comment box using AngularJS: <tr> <td colspan="5"><br/>Comments* <div><textarea class="form-control" rows="3" cols="60" ng-model="final_data.drc_scope" placeholder="Add comments here" ng-disabled="is_team==0 || isDis ...

Encountered an Error with My Protractor Script - Object Expected

Currently, I am in the process of learning automation testing for an AngularJS application. However, I have encountered an "object expected" error on line 4, which is pointing to the first line of my script. describe("Homepage", function() { it("Navig ...

How can I ensure that the scripts returned in HTML via AJAX are executed when using $.load()?

I have been trying to make an AJAX call and receive a partialView which contains some script that needs to be executed. I did some research and learned about the "eval" method, but then discovered that the $.load() method should handle this for me. Howeve ...

Tips for zooming to the middle of a div element

I'm trying to figure out how to create a zoom in effect on my large div, but I haven't been successful despite searching through many resources. My goal is to zoom into the center of the user's screen rather than just at a set position. ht ...

The element type provided is not valid: it should be a string (for built-in components) or a class/function. Utilizing SSR with Node.js, React, and React-

Playground: https://codesandbox.io/s/focused-dream-ko68k?file=/server/server.js Issue Error: Encountered an error stating that the element type is invalid. It was expecting a string or a class/function, but received undefined instead. This could be due ...

I am encountering undefined values when utilizing momentjs within Angular

My project is utilizing angular and momentJS, with the addition of the angular-moment library. You can find my current progress in this fiddle However, I am encountering an error when trying to use moment in a controller method: TypeError: undefined is n ...

Google Interview Challenge: Finding Pairs that Sum Up

My approach to solving this problem involved iterating through the array and checking if there exists an item such that the sum equals array[i] + item. If such a pair is found, I return true; otherwise, I return false. Now, my main inquiry is: How can I m ...

Is it possible to incorporate a function within a JSON object structure?

I'm working on developing a library with the main requirement being that users can only utilize JavaScript to implement it. The idea struck me to leverage JSON and AJAX for this purpose. Is it feasible to define functions within JSON? Just to clarify ...

Page reloads are disabled when Chrome devtools debugger is paused in a React app

Currently, I am in the process of troubleshooting a React application that was created using create-react-app. Whenever I attempt to reload the page while paused on a breakpoint, it results in the page stalling. The screen goes blank and is unresponsive t ...

Getting a null value for active user after completing the sign-in process

I am using local storage to store username and password. However, I am encountering an issue where the active user is returning null after a certain line of code, and I am unsure why. console.log("I am the Active user: " + activeUser); const me ...

How can I retrieve data using the angular method instead of the traditional $.ajax approach? Is $http a suitable replacement for $.ajax in Angular?

Here is the code snippet I have written. .state("dynamic", { url: "/:name", controller : 'AppHomeCtrl', templateUrl: function (params){ var myURL = params.name + '.html'; var validPage ...

Is your preference selecting made a breeze by dragging the input field?

Looking to create a form that allows users to indicate their preference between Option A and Option B by dragging a slider. I know there must be a library out there that already does this, but I can't seem to figure out what it's called to searc ...

Incorrect JavaScript switch case usage

Once again, I find myself with a question regarding JavaScript. This one seems to be an easy fix, but for some reason, I just can't seem to figure out what went wrong: I have a textbox and a button. When the button is clicked, the value should be pas ...

Tips for rearranging an item to the beginning of an array at index 0

What is the most efficient way to delete a specific object from an array and move it to the beginning? I have attempted using regular methods such as finding the index, manually splicing, and then moving the object to the top. farmer: [ { id:1, name: "na ...

Issue: It is necessary to utilize the `@babel/plugin-transform-runtime` plugin if you have set `babelHelpers` to "runtime" when using npm link

My situation involves having two interconnected React libraries: project-ui and propert-utils. project-ui relies on propert-utils, and the latter is installed within the former. "devDependencies": { "@company/project-utils": "gi ...

Examining a React component through unit testing using Jest and Enzyme

I am currently conducting unit tests on a React component. One component is importing another and utilizing its props. Below are the JSX files: class First extends React.PureComponent { render() { const { name, isSelected, onClick } = this.pro ...