Controlling Form Inputs in AngularJS: Effortlessly Disable All Controls until Server Responds

Trying to figure out the best way to disable form controls temporarily when a user clicks a "Save" or "Submit" button and data is being processed. I prefer not to use JQuery and avoid querying elements as an array based on class or attribute.

  • One idea is to mark all form elements with a custom directive called cm-form-control. This directive will listen for two notifications: "data-sent" and "data-processed". Custom code will handle pushing the second notification or resolving a promise.
  • Another option is to use promiseTracker, which unfortunately requires using cumbersome code like
    ng-show="loadingTracker.active()"
    . Not all elements have the ng-disabled attribute, and using ng-hide/show may result in buttons appearing to "dance".
  • The last resort would be to reluctantly resort to using JQuery.

Any better ideas out there?

UPDATED: Using the fieldset approach does indeed work. Here's a simple demo for those interested: http://jsfiddle.net/YoMan78/pnQFQ/13/

HTML:

<div ng-app="myApp">
    <ng-form ng-controller="myCtrl">
        Saving: {{isSaving}}
        <fieldset ng-disabled="isSaving">
            <input type="text" ng-model="btnVal"/>
            <input type="button" ng-model="btnVal" value="{{btnVal}}"/>
            <button ng-click="save()">Save Me Maybe</button>
        </fieldset>
    </ng-form>
</div>

JS:

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

angModule.controller("myCtrl", function ($scope, $filter, $window, $timeout) {
    $scope.isSaving = undefined;
    $scope.btnVal = 'Yes';
    $scope.save = function()
    {
        $scope.isSaving = true;
        $timeout( function()
             {
                 $scope.isSaving = false;
                 alert( 'done');
             }, 10000);
    };
});

Answer №1

Enclose all your form fields within a fieldset tag and utilize the ngDisabled directive as shown below:

<fieldset ng-disabled="isProcessing"> ... input elements ...</fieldset>

This will automatically disable all input elements within the fieldset.

Next, in the controller, set $scope.isProcessing to true before making an HTTP request and then back to false afterwards.

Answer №2

For those using modern web browsers, a straightforward solution is available:

  1. Create a CSS class

    .disabled {
      pointer-events: none;
      ... ...
    }
    
  2. Apply this class to ng-form

    <ng-form data-ng-class="{ 'disabled': isSaving }"> ... inputs ... </ng-form>
    

This link provides information on the support for pointer-events.

Note: Even when pointer-events: none is set, it is still possible to navigate to input elements using the keyboard.

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

Display a component from an array once user input is received in a React application

When using Timepicker inputs from Material UI and storing them in an array, I have encountered an issue. Although I can see the array with console log, I am unable to render a table or chip components from that array of objects after it has been stored. Od ...

employing JavaScript to present an image

Here is the image code I have: <img id="imgId" src="img/cart.png" style="display: none"/> After clicking a button, it triggers a JavaScript function to show the image document.getElementById("imgId").style.display = "inline" The image display ...

Using Ajax to set the file target dynamically

Let me start by saying that I prefer not to use JQuery for any suggestions. I'm not a fan of how JQuery has become the de facto standard within JavaScript. Now, onto my issue: I want to pass a variable to a function that will then use that variabl ...

Position an HTML div by using data from a JSON object

While working on my dashboard, I successfully saved data to my database using jQuery, JSON, and a generic handler. Subsequently, I managed to retrieve this data using a WebService and JSON. The structure of my database information is as follows: Upon docu ...

Limit the allowable React Component prop type in Typescript

To promote composition within our codebase, we utilize passing components as props. Is there a way to enforce type checking for the components passed as props? For instance, let's consider a commonly used Typography component throughout the codebase, ...

Choose various cells on the grid of a canvas by dragging the mouse

I am trying to incorporate a feature where users can select multiple cells on the grid chart by dragging. However, I am facing an issue with the functionality - instead of forming a square while moving the mouse, it currently draws a square when I drag and ...

Sending an Ajax request to C# code

UPDATE After some research, I discovered what seems to be the "correct way" to handle the issue by using a combination of JSON.stringify and creating a model, as explained in this thread. I still can't figure out why the original approach didn't ...

Encountering an error with Next.JS when using the "use client" directive

Recently encountered a bizarre issue with my next.js project. Every time I input "use client"; on a page, it triggers a "SyntaxError: Unexpected token u in JSON at position 0". Here's the code snippet for reference: "use client" ...

PHPMailer: Issue with File Upload Functionality

I'm having a problem with my contact form - it's working well, but I can't seem to get the uploaded files through the contact form. Here are the relevant HTML codes: <form id="contact_form" method="post" action="php/mail-advanced.php" en ...

Using radio buttons to generate a URL based on the user's selection

I currently have a set of 3 Radio Buttons along with a Select button - my goal is to dynamically change the select button based on which radio button is chosen. Here's an example of what the HTML code looks like: <INPUT TYPE="radio" id="Orange"&g ...

Angular JS Introductory Module

Currently, I am encountering an issue in AngularJS 1.2.15 marked by $injector:modulerr. Interestingly, the application runs smoothly when hosted on a MAMP Apache server locally, but encounters errors when running on a node server, generating the error mess ...

Sending information from React JS to MongoDB

I am currently facing a challenge in sending data from the front-end (react js) to the back-end (node js), and then to a mongodb database for storage. While I have successfully called the server with the data, I am encountering an issue when attempting to ...

Efficiently Managing Forms with SharePoint Online

Recently, I created a basic HTML/PHP form that collects input data and generates a company-approved email signature in HTML format. The form simply captures the information entered by users and displays it in the signature layout. Check out the form below ...

Is it possible to execute a REST call in JavaScript without utilizing JSON?

(I must confess, this question may show my lack of knowledge) I have a basic webpage that consists of a button and a label. My goal is to trigger a REST call to a different domain when the button is clicked (cross-domain, I am aware) and then display the ...

Revolutionize iPad user experience with seamless HTML5 video integration

What is the most effective method for dynamically embedding HTML5 video to ensure compatibility with the iPad? (using pure Javascript) I'm having difficulty getting this approach to work: <div id="placeholder"><script type="text/javascript" ...

Deleting tasks from the to-do list using Node.js and Express with EJS

Looking to implement functionality where each list item can be removed from a Node.js array by clicking on an HTML button using EJS and Express: I am considering placing an HTML button next to each list element so that the selected element can be removed ...

Having trouble populating the input text field with the selected value from a dropdown using JavaScript

I have implemented a JavaScript function to retrieve the id of a dropdown select with id='odrid'. The script looks like this: $('#odrid').change(function(){ $.getJSON( 'fetch.php', 'odrid='+$(&ap ...

Importing a JSON or JSONC file into a vite/typescript project can be easily done

I am looking for a way to seamlessly share my routes between my actix-web backend and Vue with Vue-Router frontend without needing separate route files. I want to define the routes on the frontend without having to make any changes on the server side. If t ...

JavaScript: Simply returning an array with no elements

As I work on refining a solution for fizzbuzz to generate an array of numbers and strings, I encountered an issue where the return statement only outputs an empty array. Interestingly, when I print the array to the console, it appears as intended with all ...

I am encountering an issue in Nextjs with mongoose where it seems that the function mongoose.model() is not

In my E-commerce app built with Next.js and utilizing Mongoose, I defined a productSchema (models/Product) like this: const mongoose = require("mongoose"); const productSchema = new mongoose.Schema( { title: { type: String, required: true } ...