Developing an Angular form using pure JavaScript scripting

Every year, I find myself faced with a tedious task of submitting around 100 rows of data through a cumbersome form on a website. Instead of wasting hours manually inputting the information row by row, I decided to invest my time in writing some JavaScript code to automate the process.

For the past three years, my code has worked flawlessly. However, now that they have switched to an Angular JS application, I am struggling to figure out how to interact with the forms as if they were being filled out by a real person.

Take this Angular form as an example: https://codepen.io/sevilayha/full/xFcdI/

Previously, I could simply set the values of the form elements, simulate clicking on them to trigger a "dirty" state, click submit, and be done. But with Angular apps, this approach no longer seems to be effective:

function setAndClick(selector, value) {
  const el = document.querySelector(selector);
  el.value = value;
  el.click();
}
setAndClick('[name="name"]', 'Happy Robot');
setAndClick('[name="username"]', 'happyrobot');
setAndClick('[name="email"]', '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef878e9f9f96af9d808d809bc18c8082">[email protected]</a>');

Although manually clicking on the fields after they have been filled by the script does trigger a "dirty" state, I have not been able to identify any event (such as change, keyup, keydown, etc.) that can programmatically trigger it.

Do you have any insights or suggestions on how I can successfully fill out and submit a form in an Angular App using plain JavaScript?

Answer №1

One interesting tip is that you can access the angular scope of any DOM element by using the following code snippet:

angular.element(theElement).scope()

This scope can be leveraged for various purposes outside the angular application itself, such as troubleshooting tasks like the one you're currently working on. It comes in handy especially when debugging an angular app through developer tools.

To demonstrate this technique quickly, I have modified your Pen to update the "Name" field:

https://codepen.io/anon/pen/pwPdqM

The function responsible for the task is as follows:

function dirtyByCode() {
  // Access the input element wrapped as an angular element
  var elName = angular.element(document.getElementsByName("name")[0]);
  // Obtain the angular scope for this specific element
  var $scope = elName.scope();
  // Invoke $setViewValue to modify the data and set the state to dirty
  $scope.userForm.name.$setViewValue("Simon");
  // Update the form itself by invoking render
  elName.controller("ngModel").$render();
}

A notable advantage of this approach is that you do not need to utilize $apply or be concerned about the $digest cycle.

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

A beginner's guide to handling multiple events with @click in Vue.js

In my project, I am developing a task manager application utilizing Vue.js, Vuetify, and Firebase. When the user clicks on "Add new note," a Vuetify dialog box pops up, prompting them to input data. Once they click save, the dialog box closes, and the inpu ...

Determine the point spread using Jquery

Trying to figure out the point spread and determine the winner of a game based on the entered scores. I've created a function to calculate the total number of points and another function to calculate the point spread and assign a winner label. However ...

Is there a way to eliminate the default bootstrap stylings?

Currently working on a project where I am utilizing bootstrap scripts to simplify things. However, upon adding everything along with the CSS, bootstrap ends up changing parts of my page that I did not intend for it to do. Is there a way to remove these u ...

Change the appearance of Material UI Select component when the onChange event is triggered

Typically, MaterialUI's Select component maintains focus after an option is selected. This behavior can be observed in all their documentation examples here. My objective is to have the element lose focus once an option is chosen. This is how my curr ...

Error in the syntax of PHP code within an external .js file

Despite my best efforts, I have been unable to find a solution to my current problem. I am attempting to insert a PHP variable into my external .js file. The goal is to store the PHP variable in a JavaScript variable and then use ajax for database communi ...

Create a PHP array containing strings and generate two-dimensional arrays as a result

One issue I encountered in PHP involves creating an array with a string while also cutting some images. Within my code, buildProject.php is included in index.php (with session_start(); for _session at the top). buildProject.php <?php $list_project = ...

What is the best way to access controls instance in react-three-fiber?

Is there a method to retrieve the controls instance of the scene in react-three-fiber? I am aware that it can be obtained using a ref, for example: import { useFrame } from 'react-three-fiber' const controls = useRef() useFrame(state => cont ...

Callbacks for successful and failed responses when using AngularJS $resource

I've written a simple code snippet that's functioning as intended, but I'm looking to incorporate success and error callbacks. Here's the current code snippet: angular .module('studentInfoApp') .factory('Student& ...

Control the scope value using an AngularJS directive

I have a model with values that I need to modify before presenting them to the user. I have checked the documentation but might be overlooking something. For example, I would like to format my variable in this way: <span decode-directive>{{variable ...

What is the best way to replicate an HTML element's style properties in JavaScript or jQuery?

Is there a way to clone the style object of an element so that I can reset the styles back to their original values after making changes? Here's an example: el.style.left; // 50px curr_style.left; // 50px; /* Modify the elements style. The ...

The JavaScript function is not executing the Node.js code as expected

Currently, I am utilizing Twilio to send a sample message when running the provided code in the terminal: var accountSid = '...'; var authToken = '...'; var twilio = require('twilio'); var client = new twilio(acco ...

"Troubleshooting: Express.js route fails to retrieve data from database when querying by _id field

I've set up the following Express.js route router.post('/', async (req, res) => { try { console.log(`Request Body :\n${req.body}`); const {orderIDs} = req.body; console.log(`Order IDs : \n${orderID ...

AngularJS implementation that disables a button when the input field is empty

As I delve into learning angular JS, I am facing a challenge. I want to disable the button using the "ng-disabled" attribute while my input fields for "login" and "password" are empty. However, the default text in the login input is "LOGIN" and in the pass ...

Issue with Three.js Shader rendering improperly on a specific custom geometry mesh surface

I am facing a challenge with applying a shader to a single face Mesh in Three.js. Upon applying the shader material to the mesh, it seems to only read a single pixel of the shader and apply that value to the entire face. I have tested this using the follo ...

If every div within a specific section is not visible, then hide the entire section

In the sections on my webpage, I have multiple divs displayed. Each section contains several child divs that can be hidden based on a selection from a dropdown field. This functionality is working smoothly. Now, I am looking to improve this by hiding the ...

CSS - Ensure the parent stays open and the submenu remains highlighted upon selection

I have integrated a CSS Vertical menu with submenus into an ASP.Net application on the master page. Clicking on each menu item directs to different aspx pages. However, when clicking on a submenu within an expanded parent menu, the page redirects as expect ...

Utilizing an iPad to control and modify the content displayed on an external monitor

I am uncertain about the exact scope of this project and would appreciate input from those with prior experience. The project involves creating a mobile site that will act as a framework for displaying content. The 'app' will feature a simple li ...

Get rid of the arrow that is displayed when using the `time` input type in HTML5

Recently, I encountered an issue with the default HTML5 code snippet. My custom background looked perfect except for a pesky black arrow appearing on the right side. In this image, you can see the problematic black arrow that needs to be removed. I attemp ...

The error message "Uncaught ReferenceError: req is not defined with [email protected]" indicates that the variable

Discovered a helpful post that seems to address the problems. https://github.com/angular/angular-cli/issues/8359 I'm unsure about the steps to take next to resolve this issue. Can anyone clarify? Could you please advise on which version of Angular ...

Send an array to a function with specified criteria

My current code successfully splits an array, but I need to pass a value when the array condition is met. For example, here is how the value is split into an array: var myArr = val.split(/(\s+)/); If the array in position 2 is empty, I need to use ...