Submitting a form across controllers in AngularJS: What you need to know

<div ng-controller="ctrl1">
    <form name="form1" ng-submit="submitForm()">
        <input type="text" name="email" />
    </form>
</div>

<div ng-controller="ctrl2">
    <button> Submit </button>
</div>

In this scenario, I am seeking a way to trigger the form submission action from ctrl2 for a form that exists within ctrl1.

What is the best approach to accomplish this using AngularJS?

Answer №1

One way to handle this scenario is by triggering an event when the button is clicked, and then utilizing $rootScope to broadcast the event downwards. The controller (ctrl1) can then listen for this event and submit the form accordingly.

Answer №2

To accomplish this task, you have the option of utilizing $rootScope, services, or event broadcasting.

app.controller('ctrl2',['$scope','$rootScope',function($scope,$rootScope) {
    $scope.submitForm = $rootScope.mainSubmit();
}]);

app.run(function($rootScope){
    $rootScope.mainSubmit =function(){
        console.log("hey");
    };
})

Answer №3

In order to communicate between two controllers, you can trigger an event from the second controller and catch it in the first one.

function ControllerOne($rootScope) 
{
  $rootScope.$on('submitEvent', function(event, args) {
      //handle form submission here
  });
}

function ControllerTwo($scope,$rootScope) 
{
  $scope.submit=function(){
    $rootScope.$emit('submitEvent', args);
  }
}
<div ng-controller="ControllerOne">
    <form name="form1" ng-submit="submitForm()">
        <input type="text" name="email" />
    </form>
</div>

<div ng-controller="ControllerTwo">
    <button ng-click="submit()"> Submit </button>
</div>

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

What causes the promise to fail when executed outside of the loop?

I have been working on adding fusionCharts dynamically to an AngularJS page. I load chart data into a model object, and while the charts do display, they show "No data to display" content. My app.js: (function () { var modelListOfCharts = ["1", "4", "5" ...

Iframe Interactivity

My goal is to create an interactive iframe that will match the current parent URL (). For example, if I have an iframe pointing to http://www.google.com and click a link within the iframe, it should update the parent URL to , and then load the clicked con ...

Acquiring an icon of a program using its handle

I am looking for a way to extract a program's icon from its handle, which I acquired using User32.dll with EnumWindow/FindWindow. While I am aware of ExtractAssociatedIcon, it seems to work from a file instead of a handle. My question is how can I con ...

Displaying retrieved data following AJAX request in ASP.NET MVC is currently not functioning

I have a situation where I need to populate two <p> fields with text Below is the HTML code snippet: <p id="appId" style="visibility: hidden;"></p> <p id="calculationId" style="visibility: hidden;"></p> I am making an AJAX ...

Ways to resolve the issue of code not relocating the channel within a specific

The script I wrote to create a new category and channel produced an error message: TypeError: Cannot read property 'hasOwnProperty' of undefined. The issue occurs when the channel is not properly placed within the category. Here is the code snipp ...

Displaying a collection of items using Rails, implementing form_for and integrating Ajax functionality

Looking to display a list of "Interests" for users to "follow" by clicking on a button linked to the Interest's image. Once the follow button is clicked, the Interest and its image should be removed from the list. Attempting to use a hide function in ...

Loop through the unnamed object

Here's the object that I am working with, which contains arrays: https://i.sstatic.net/WPAF4.png To extract its key values for further use, I'm trying to iterate over it using for in loop like this: for (let key in gameObj){ console.log(key ...

Limit the Jquery selection specifically to elements on the modal page

Recently I encountered an issue with a webpage that opens a modal form. The problem arises when the validation function, written in JQuery, checks all fields on both the modal and the page beneath it. //validate function function validateFields() { v ...

The div swiftly clicks and moves beyond the screen with animated motion

Here is a code snippet that I am working with: $(document).ready(function(){ $(".subscriptions").click(function (){ if($(".pollSlider").css("margin-right") == "-200px"){ $('.pollSlider').animate({"margin-right": '+ ...

Exploring the option of showcasing multiple json_encode data on a pie chart

Hey there! I'm currently utilizing Chart.js to generate a pie chart by retrieving data from the database: <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> <script> var ctx = document.getE ...

developing a star rating system for a mobile website

Can star ratings be implemented in a mobile website using HTML, CSS, and JS? The HTML code for the stars is as follows: <div class="rating"> <span>☆</span><span>☆</span><span>☆</span><span>☆</sp ...

Is it possible to incorporate button classes from the <a> tag into a JQuery fade in/fade out function?

My jQuery image thumb Slider features thumb buttons that link to different div elements. When a user clicks on a thumb button, I want the associated div to smoothly fade in, replacing the previous one. The goal is to have a seamless transition between the ...

Nested ngInclude causing binding to fail

I am managing a list of tasks that may have subtasks and I need to display only the root level initially. Users can then load each branch as needed. To achieve this, I am utilizing nested ng-includes and ng-init to pass the task list. Below is the template ...

What is the proper way to utilize the decodeURIComponent function?

router.get("/stocks/authed/:symbol", function (req, res, next) { req.db .from("stocks") .select("*") .modify(function(queryBuilder) { if (req.query.from && req.query.to) { queryBuilder.whereBetween('timestamp&apos ...

Error: Unable to access properties of an undefined value (trying to read 'type') within Redux Toolkit

Looking for help with this error message. When trying to push the book object into the state array, I encounter an error. Folder structure https://i.stack.imgur.com/9RbEJ.png Snippet from BookSlice import { createSlice } from "@reduxjs/toolkit" const ...

The function is undefined (near '... map ...')

Whenever I tap on the Pressable element in the JSX, an error pops up saying: "Undefined is not a function (near '... wines.map ...')." The issue seems to be originating from the wines.map loop in the JSX code. I am uncertain about what might be w ...

Alternatives to socket.removeAllListeners(); for client-side operations

I recently encountered a challenge similar to the one discussed in the thread Enhancing this AngularJS factory for compatibility with socket.io. However, the solution provided seems to reference a function that is no longer supported. Can anyone advise o ...

Are you facing difficulties while trying to utilize useContext in your React application?

I have a basic React application where I need to implement useContext. (by the way, I am using Vite + React) Below is the code for my Context.jsx file: import React, {useContext} from 'react'; const emailContext = React.createContext(); expor ...

Loading a GLTF model directly from a file input with ThreeJS

When using ThreeJS, I want to allow the user to load any GLTF model they choose to display. To achieve this, I have implemented a file input tag where the user can click and select a gltf-file to upload from their file browser: <input id="selectedM ...

Is there a method to develop an application utilizing the local web page as the interface?

Just a few days ago, I came up with the idea to create my own user-friendly "interface" for organizing and accessing some of my personal files. Having all related data, images, and links easily accessible with just a few clicks sounded very convenient to m ...