angularjs controller cross-validation for forms

I am faced with a dilemma involving two controllers: btnController and formController. Specifically, I need to submit a Form from another controller action while ensuring that the function in the controller is only called when the Form Validation is Valid. Currently, if a user attempts to submit the form without entering any information, the submit function is still triggered.

How can this issue be resolved?

Below is my code snippet:

<div ng-app='app'>
    <div class='header' ng-controller='btnController'>
        <button ng-click='submit()'>
            Submit Form
        </button>
    </div>

    <div class='container' ng-controller='formController'>
        <h2>Form</h2>
        <form id='myform'>
            <input ng-model='name' placeholder='name' required/>
            <span style="color:red" ng-show="myform.name.$dirty &&      myForm.name.$invalid">
                <span ng-show="myform.name.$error.required">Username is required.</span>
            </span>
        </form>
    </div>
</div>


(function(){
    var app=angular.module('app',[]);
    app.controller('btnController',function($scope){
        $scope.submit=function(){
            angular.element(document.getElementById('myform')).scope().submit();
        }
    });

    app.controller('formController',function($scope){
        scope.name;
        $scope.submit=function(){
            alert($scope.name);
        }
    });
})();

Feel free to check out the example on JsFiddle

Answer №1

Update:

You will need to ensure that the submit() function in your 'formController' is only called when the form has been validated:

app.controller('btnController',function($scope){
    $scope.submit=function(){
      var elementScope = angular.element(document.getElementById('myform')).scope();
      if(elementScope.myform.name.$valid)
         elementScope.submit();
    }
});

Check out this Jsfiddle link: https://jsfiddle.net/oucdodf8/

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

Three.js: Wanting to create objects and add motion along a curved path

In an attempt to create a unique effect, I am exploring the idea of spawning a series of objects on a setInterval and assigning each object a customized animation on a path using requestAnimationFrame. I have successfully added one object and animated it a ...

Flow object with Angular using ng-flow: Existing flow object

Just a quick question that I can't seem to find an answer for on my own or through searching online. Currently, I have a button set up for clicking and uploading files. However, I also want to incorporate drag and drop functionality using the same fra ...

The caching of AJAX POST requests is a common occurrence

In my web application, I have implemented a functionality where a POST request is sent to the URL /navigate.php and it works correctly. However, the challenge arises when the application needs to function offline. In such cases, I aim to display a notifica ...

What steps can I take to position tsParticles behind all other elements in my NextJS project?

In full disclosure, I am not a web developer, so my setup may be incorrect. Currently, the particles are covering all other elements on the page. I would like them to be positioned behind the rest of the elements and only show as a background. import Imag ...

The method this.$el.querySelector does not exist

The data retrieved from the database is inserted into the input fields and submitted as a form. This data is an object that passes the value to the database. However, when I trigger this form, an error occurs. See example of the error <input id=" ...

Using React Native to dynamically change color based on API response

I'm currently working on a React Native project and I have a requirement to dynamically change the background color of a styled component based on the value retrieved from an API. However, I'm facing some challenges in implementing this feature. ...

Issue with React Material-UI drawer not functioning properly when invoking a child component function from the parent

Here is a piece of code I have for the App.js file: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Child from './child'; class App extends Component { render() ...

Converting JavaScript code to React requires excluding jQuery

I have been working on updating my old JavaScript code to make it compatible with React. The main goal is to integrate external data into a 3rd party form. Here is the original JS code: <script charset="utf-8" type="text/javascript" ...

Leveraging React hooks to combine an array and an object within an array

Struggling to incorporate an array and an object into another array. This is the setup in my constructor: const [dashboard, setDashboard] = useState({ loading: true, data: [], address: '' }) This is how I envision the final data structure: { ...

Saving Information from an HTML Form Input?

I am currently working on a form that collects information about employees including their name, age, position, and details. When the "Add Record" button is pressed, this information should be added to a designated div. Although I have set up the Object C ...

Discover the method for retrieving information through AJAX requests and dynamically displaying or hiding content based on the received

Currently, I'm in the process of developing a PHP script that outputs a numerical value indicating the number of unread messages. The snippet below showcases my code that triggers the PHP function every 30 seconds: setInterval(function (){ ...

Step-by-step guide for implementing an "on change" event for a select box within a dialog box

I recently wrote an HTML code snippet like this: <div id = "dialog-1" title = "Dialog Title goes here..."> <select id= "lang" name= "lang"> <option value="1"> TEXT </option> <option value="2"> HTML </op ...

Using jQuery to toggle the visibility of divs depending on the selection of multiple checkboxes

I found this code snippet that I need help with. <div class="row"> <div class="col-xs-4"> <label class="checkbox-inline"><input type="checkbox" value="draft">Draft</label> </div> <div class="c ...

Wave Filter in SVG

While attempting to create a fisheye-esque filter in my SVG, I came across this interesting codepen example: http://codepen.io/johanberonius/pen/RopjYW The effect works well, but I would like it to be a bit more pronounced. Unfortunately, I am unable to m ...

Encountered a runtime error while trying to insert a list item <li> into a paragraph <p> element

Take a look at this code snippet: <%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication18._Default" %> <!DOCTYPE html> <html> <body> <p id="someId"></p& ...

Discover the unseen: The ultimate guide to detecting visible objects in a (deferLoad) event

I'm utilizing the (deferLoad) method to load an image gallery in a more controlled manner. Is there any event available that can inform me about which items are currently visible? The main goal is to load a set of data along with an image path, and t ...

Error 401 encountered while accessing the Binance API using Ionic and Angular

function makePrivateCall(apiSecret, apiKey, endpoint, data = null, isGetRequest = true) { const timestamp = Date.now(); const recvWindow = 60000; //maximum allowed, default 5000 var obj = { apiSecret, ...data, timestamp, ...

Interactive table with Draggable feature supported by Bootstrap Vue

After tirelessly searching for a solution to drag and drop rows on a Bootstrap Vue table, I finally stumbled upon a functional version here: Codepen I attempted to integrate this code into my own table: Template: <b-table v-sortable="sortableOptions ...

Tips for personalizing the appearance of tooltips when hovering over bars on a Chart.js bar chart

My goal is to create a bar chart similar to the one shown below. I am working on this project within an AngularJS platform and utilizing the Chart JS library for the chart. The issue I am facing is that I am unable to display a tooltip when hovering over ...

AngularJS Mapping between two JSON files

What is the most effective way to map data between 2 JSON files in AngularJS? I need to connect and display information from these files in a table. JSON File 1 [{ "year": 2013, "doctor": "Dr. Smith", "illness": "Flu", "apptdate": " ...