Retrieve a form (for verification purposes) from a separate AngularJS component

I'm facing an issue with accessing a form from one component to another in my project. One component contains a form, and the other has navigation buttons that, when clicked, should validate the form before moving on to the next step. However, I always encounter the problem of the form being undefined when trying to access it from another component. Is there a way to successfully access the form from another component, and if so, how can I achieve this?

https://i.sstatic.net/UALJs.png

Here's my sample code in plunker

Index.html

<!DOCTYPE html>
<html>

<head>
  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ffef1f8eaf3fedaffecfdffa1aaa1b0">[email protected]</a>" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="app">

  <form-component></form-component>
  <nav-component></nav-component>
</body>

</html>

script.js

// Code goes here

function checkForm(form) {
  if (form) {
      if (form.$valid) {
        alert("Form is valid!");
      } 
      else
      {
        alert("Form is invalid!");
      }
    }
    else {
      alert("FAILED! Form is undefined!");
    }
}

function formController() {
  var model = this;

  model.goToNextStep = function(form) {
    model.form = form;
    checkForm(form);
  };

}

function navController() {
  var model = this;

  model.goToNextStep = function(form) {
    model.form = form;
    checkForm(form);
  };

}
var app = angular.module("app", []);

app.component("formComponent", {
    template: `
      <div class="container">
        <form name="mainForm">
          <p>When you click the button that exists in the same component
             as the form, everything works fine.\
          </p>
          <input type="text" name="test123" value="THIS IS A TEST" />
          <button type="button" ng-click="model.goToNextStep(mainForm);">
            Submit Form
          </button>
        </form>
        <br /><strong>formComponent model:</strong> <pre>{{model | json }}</pre>
      </div>
    `,
    controllerAs: "model",
    controller: [formController]
});


app.component("navComponent", {
    template: `
      <div class="container">
        <p>When you click the button that does NOT exist in the same
           component as the form, it doesn't work.
        </p>
        <button type="button" ng-click="model.goToNextStep(mainForm);">Submit Form</button>
        <br /><br /><strong>navComponent model:</strong>
        <pre>{{model | json }}</pre>
      </div>
    `,
    controllerAs: "model",
    controller: [navController]
});

Answer №1

One strategy involves nesting the two components within an ng-form element:

  <ng-form name="top">
    <form-component top-form="top"></form-component>
    <nav-component top-form="top"></nav-component>
  </ng-form>

Utilize one-way < binding to link the two to the top form:

app.component("formComponent", {
    bindings: {topForm: "<"},
    template: `
      <div class="container">
        <form name="mainForm">
          <p>If you click the button in the same component as the form, everything functions correctly.</p>
          <input type="text" name="test123" value="THIS IS A TEST" />
          <button type="button" ng-click="model.goToNextStep(model.topForm);">Submit Form</button>
        </form>
        <br /><strong>formComponent model:</strong> <pre>{{model | json }}</pre>
      </div>
    `,
    controllerAs: "model",
    controller: [formController]
});
app.component("navComponent", {
    bindings: {topForm: '<'},
    template: `
      <div class="container">
        <p>If you click the button that is NOT located in the same component as the form, it will not work as intended.</p>
        <button type="button" ng-click="model.goToNextStep(model.topForm);">Submit Form</button>
        <br /><br /><strong>navComponent model:</strong> <pre>{{model | json }}</pre>
      </div>
    `,
    controllerAs: "model",
    controller: [navController]
});

The DEMO on PLNKR

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

Step-by-step guide for implementing a scroll event on FancyBox

I am facing an issue with a large fancybox popup that contains a scroll function. I need to find a way to attach an event to this fancybox popup when scrolling. I have tried several different events, such as: $('.fancybox-inner').off("scrol ...

Exploring Scope Inheritance in AngularJS

Within the parent controller scope, I have initialized selectedItem as 'x'. Subsequently, in the child scope, selectedItem is declared using ngModel: <div ng-app> <div ng-controller="CtrlA"> <div ng-controller="CtrlB"> ...

Having issues with templateURL not working in AngularJS routeProvider

I've been experimenting with ngRoute and I'm facing an issue with templateURL not working as expected. The functionality works perfectly except for when I attempt to use templateURL. Here are the 4 files involved: test.html <p>{{test}}&l ...

When the "open" prop is set to "true", the DRAWER component from @material-ui/core fails to display

Help Needed: I'm struggling to make the drawer component open when the variant prop is set to "temporary". Material-UI Package Used: @material-ui/core I have integrated Material UI's drawer component into my custom Nav component. However, I am ...

Encountering an issue while attempting to replicate the Spotify app on localhost:3000. The error message "TYPEERROR: Cannot read property 'url' of undefined" is hind

As a first-time user of stackoverflow, I am unfamiliar with its rules and regulations, so I apologize in advance for any mistakes I may make. Currently, I am attempting to create a Spotify clone using React. Everything was going smoothly until I completed ...

Enhancing your Angular JS web application with ngCordova

As a beginner in Angular development, I am exploring the process of creating a responsive form within an AngularJS web application to enable users to upload files or photos from a mobile browser. Before proceeding with the uploads, I need to access and che ...

Ways to limit date selection with JavaScript or jQuery

On my webpage, I have two date fields: fromDate and toDate. My goal is to prevent submission if the difference between the dates is more than 7 days. Despite implementing a script for this purpose, it doesn't seem to be working... var d1 = new Da ...

Filtering a table using jQuery based on the class or data attributes

Issue arises when selecting the first "Icon" shows "Not found", then opting for "Talisman" does not display. It should show "Not Found". Is this achievable? Add the classes f-Icon, f-Ring, f-Neck. Then search for the value by class. Select either "Icon R ...

What is the best way to import modules in Typescript/Javascript synchronously during runtime?

I have a Typescript class where I am attempting to perform a synchronous import, however, the import is being executed asynchronously. My code snippet looks like this: --------------100 lines of code-------------------- import('../../../x/y/z') ...

"Exploring the world of RGB color schemes in ThreeJS

I have a collection of points stored in a large string, with newline characters \n separating each point. Each point is saved as x y z r g b, where r g b values fall between 0 and 255. After reading through the ThreeJS documentation, I found a way to ...

Tips for effectively loading data of a specific user or event into a bootstrap modal in Laravel using AJAX

I'm having some trouble loading Event data into my bootstrap modal in Laravel. This is all new to me as I'm just getting started with AJAX. Can someone please take a look at what I've done so far? Modal Template <div class="modal fa ...

Discovering the presence of a NAN value within a JSON string

Consider the following scenario: I have a function that receives jsonData in JSON format, and I want to validate the variable jsonData to check for NaN. How can I achieve this? function save() { var jsonData = getEnteredValue(); $.ajax({ ...

Exploring the seamless integration of Next.js, TypeScript, and useContext across

Revision: I realized that I had forgotten to include the following line of code in my Header.tsx component: import Link from 'next/link'; After rectifying this oversight, everything started functioning properly. I am currently struggling with ...

Automatically add values after successful Facebook login

Currently, I am working on a Cordova project where I have implemented Facebook login for user authentication. While the login is functioning correctly, I am facing an issue where I need to manually press a button with the ID getinfo in order for the values ...

Cache for AngularJS $http.jsonp requests

I'm struggling with caching a JSONP request and have tested out different approaches without success. I attempted $http.jsonp(url, { cache: true }) and $http({ method: 'JSONP', url: url, cache: true }), but neither worked as expected. As a ...

What could possibly be causing this element to shift side to side (in IE only) during the CSS animation?

UPDATE: Issue occurring on Internet Explorer 10, Windows 7 When using the transform property to adjust the horizontal position of an element during animation, the vertical value is updated as well. However, despite setting the horizontal value to the same ...

Arrangement of watch attachment and $timeout binding

I recently encountered a component code that sets the HTML content using $scope.htmlContent = $sce.trustAsHtml(content). Subsequently, it calls a function within a $timeout to search for an element inside that content using $element.find('.stuff' ...

Ways to verify whether a user is not defined

My code includes a command that sends a Direct Message to a user, with the user being specified as follows: let user; if (message.mentions.users.first()) { user = message.mentions.users.first(); } else if (args[0]) { user = message. ...

An issue occurred while testing with React-Native Testing Library/Jest, where the property 'TouchableOpacity' could not be read

I am currently in the process of conducting tests using jest and react-native testing. Unfortunately, I have encountered an issue where TouchableOpacity is not being recognized and causing errors. Card.test.js import Card from "../Card" import R ...

My Gatsby website is being rendered in its HTML form on Netlify

The website build is located at . It appears that the javascript functionality is not working, and only the html version (usually meant for search engines) is being displayed. It seems like this issue is only affecting the home page. You can check out the ...